From 8f0e67f3ac493380b7272915f5cf55c7a190cc11 Mon Sep 17 00:00:00 2001 From: Matthew McEachen Date: Sun, 17 Dec 2023 22:53:03 -0800 Subject: [PATCH] v2023.12.0-alpha.6 --- CHANGELOG.md | 8 ++++++++ VERSION.json | 10 +++++----- bin/info.js | 2 +- bin/list.js | 2 +- bin/logcat.js | 2 +- bin/logtail.js | 2 +- bin/main.js | 2 +- bin/photostructure.js | 2 +- bin/sync.js | 2 +- bin/web.js | 2 +- bin/worker.js | 2 +- package.json | 2 +- photostructure | 2 +- public/3rd-party-licenses.txt.gz | Bin 47174 -> 47174 bytes public/app/about.css.gz | Bin 3825 -> 3825 bytes public/app/about.css.map.gz | Bin 1257 -> 1257 bytes public/app/about.js.gz | Bin 4515 -> 4515 bytes public/app/app.css.gz | Bin 9778 -> 9778 bytes public/app/app.css.map.gz | Bin 3799 -> 3799 bytes public/app/app.js.gz | Bin 112204 -> 112204 bytes public/app/health.css.gz | Bin 5446 -> 5446 bytes public/app/health.css.map.gz | Bin 1829 -> 1829 bytes public/app/health.js.gz | Bin 69915 -> 69915 bytes public/app/install.js.gz | Bin 5876 -> 5876 bytes public/app/settings.css.gz | Bin 6117 -> 6117 bytes public/app/settings.css.map.gz | Bin 2116 -> 2116 bytes public/app/settings.js.gz | Bin 11206 -> 11206 bytes public/app/splash.css.gz | Bin 1408 -> 1408 bytes public/app/splash.css.map.gz | Bin 558 -> 558 bytes public/app/splash.js.gz | Bin 5033 -> 5033 bytes 30 files changed, 24 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17a10dd..41c190e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,12 @@ This is a detailed list of changes in each version. +## v2023.12.0-alpha.6 + +**Released 17 December 2023** + +- ๐Ÿ› Reverted alpha.5 `WorkQueue` job dequeuing tweak (as it seemed to cause lower cpu systems to never do work) + ## v2023.12.0-alpha.5 **Released 17 December 2023** @@ -43,6 +49,8 @@ This is a detailed list of changes in each version. - ๐Ÿ“ฆ Added `jpegtran` health check. You know you all wanted it. +- ๐Ÿ“ฆ `WorkQueue` job dequeuing tries to take into account system load to avoid overscheduling + ## v2023.12.0-alpha.3 diff --git a/VERSION.json b/VERSION.json index 8374c35..d6991e0 100644 --- a/VERSION.json +++ b/VERSION.json @@ -1,13 +1,13 @@ { - "version": "2023.12.0-alpha.5", + "version": "2023.12.0-alpha.6", "versionMajor": 2023, "versionMinor": 12, "versionPatch": 0, "versionPrerelease": [ "alpha", - 5 + 6 ], - "release": "2023.12.0-alpha.5+20231217214814", - "gitSha": "9cdc7207350c3cab07b8b5255f2134dc354de3a3", - "gitDate": "2023-12-18T05:48:14.000Z" + "release": "2023.12.0-alpha.6+20231217225159", + "gitSha": "0ed4df2dc131e503da6a162b731b022c60a58207", + "gitDate": "2023-12-18T06:51:59.000Z" } diff --git a/bin/info.js b/bin/info.js index 655c8e3..5ea82ca 100755 --- a/bin/info.js +++ b/bin/info.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),s=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),s=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:s}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const r=i(6113),s=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:s}=i(35740);s||(s=e=>null!=e&&e instanceof r),e.exports=s},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:s}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),s=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),s=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:s}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),s=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),s=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),s=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),s=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:s}=i(42421),{post:n}=i(97362),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),s=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),s=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),s=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),s=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),s=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),s=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(s.isProd?"":`-${s.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),s=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return D(e,t,i).index}function D(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=D(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=E,t.collectBatched=function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const s=r(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class D extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:s.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=D,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class s{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=s},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let s=!(0,r.noColor)();function n(e,t){return i=>s?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){s=e??!(0,r.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),s=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),s=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),s=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),s=i(4866),n=i(98250);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),s=i(40786),n=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),s=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){s(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),s=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),s=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),s=i(74269),n=i(78109);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),s=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),s=i(51498);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),s=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const s=r(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&s.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=s.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},46954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(43383),s=i(49849);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),s=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,s]of(0,u.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,u.keys)(e))if(r[n]=t(n,e[n]),s++,(0,l.gt)(s,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),s=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const D={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},E={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,D)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,E);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),s=i(39784),n=i(21142);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const s=i(5712),n=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),D=i(4586),E=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),O=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),A=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))O().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,l.isEmpty)(s))return O().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){O().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){O().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){O().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(O().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,E.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,s.pidExists)(r)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),s=t.getTime(),n={...e,cmd:r,startTime:s};return await i.writeJson_(n),O().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void O().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{O().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,D.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function E(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=D,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],O))}());return(0,o.sortBy)(e.filter(D),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(E([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[s.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=E;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===s.default.pid))||r.push({pid:s.default.pid,start:new Date(v.StartTs),cmd:"node "+s.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),s=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),s=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...s)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=s,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return s.promise}(...s)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),s=i(82798);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),s=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,s.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const s=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return s.setShim=e=>{i=e},s.hasShim=()=>null!=i,s}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),s=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,s.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),s=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),s},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),s=this.valueOf(this.store[r]);if(e===s)return{found:!0,index:r};e>s?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),s=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),s=i(18991);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+s+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const D=/^['โ€˜โ€™].*['โ€˜โ€™]$/,E=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),D.test(e)||E.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function D(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=D,t.paddedPositionalDiff=function(e,t,i=8){return D((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),s=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),s=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},46080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(39784),s=i(13779),n=i(1440),a=i(43414),o=i(67654),l=i(92356);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},67654:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(24603),o=i(66776),l=i(75556),u=i(61570),c=i(17078),d=i(84593),h=i(85563),f=i(7162),m=i(34928),p=i(72461),g=i(32148),y=i(43414),v=i(65642),w=i(74873),b=i(27446),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} โ‰  ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} โ‰  ${r.aKey}:${r.aValue})`}function D(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const D=P(e,i,"make",_)??P(e,i,"model",_);if(null!=D)return D;const E=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(E,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(E)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:k});const x=(0,s.compact)((0,u.values)(k));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos โ‰  images",t.whyNotSameAsset=function(e,t,i){{const i=D(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=D(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==D(e,t)},t.whyNotSimilarAssetFile=D},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),s=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const D=["make","model","rating","cameraId","imageId","lensId","geohash"];function E(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of D)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=E,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of E(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(92332)),n=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),D=i(46234),E=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class O{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new s(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,D.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new E.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===D.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==D.PromiseStates.pending}get isResolved(){return p(this,o,"f")===D.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===D.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,D.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,D.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=O,s=O,m=function(e){if(p(this,o,"f")===D.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}},r=new WeakMap,s=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=r.isTest?e:e||s}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,s,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,s,"f")?void 0:Date.now()-d(this,s,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,s,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),s=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let s,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:s):(n=!0,s=(0,r.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>s,o.force=async()=>(await s,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),s=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(s)?(0,d.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=s?b.PermissivePromises:new b.Promises(i,(()=>s))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(s);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){s=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},39506:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),s=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,s.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),s=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,n.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function D(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(s.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=D,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let E=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...D(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(s);if((0,m.isLogged)("debug")&&!E){E=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(s),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return s}t.childEnv=k},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(17718)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),D=i(79141),E=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function O(e,i,r,s=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),s-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function A(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),O(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=A(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,E.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||s?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new D.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),O(s.default.spawn(e,t,n),e,t,i)},t.execFile=A,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95298:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),D=i(45512),E=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,E.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,D.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const s=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=s?a.join("$library",i.posixPathFrom(s)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),s=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,s.exit)(0)})),e.parse(s.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),s=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,s.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),s=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(43414),s=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(r.Settings.logColor.envValue=!1),(0,s.map)(e.color,(e=>r.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(43414),s=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),s=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),s=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>D(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function D(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=D;const E=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function I(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function O(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(E,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return O(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=O,i.c[i.s]===e&&console.log(D([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),s=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,D=(y+v)/2;let E;y*v==0?E=w+b:(E=(w+b)/2,E-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,E+=2*(E<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(E-Math.PI/6)+.24*Math.cos(2*E)+.32*Math.cos(3*E+Math.PI/30)-.2*Math.cos(4*E-63*Math.PI/180),C=1+.015*k/(0,s.sqrt)(20+k),F=1+.045*D,I=1+.015*D*x,O=30*Math.PI/180*Math.exp(-1*((180/Math.PI*E-275)/25)**2),A=2*(0,s.sqrt)(Math.pow(D,7)/(Math.pow(D,7)+Math.pow(25,7))),L=-1*Math.sin(2*O)*A;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),s=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of D({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),E(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),O=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(O),pixelCount:f.length}),{dominantColors:O,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function D({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),D({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function E(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=D,t.dominantColorsFromModes=E,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),s=i(61570),n=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),s=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),s=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function D(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function E(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=D(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=D,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):E(e)},t.datedToDateTime=E,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),s=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),s=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),s=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),s=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),s=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function D(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class E{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tD(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return s.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new E(t.year,t.month,t.day)}}function k(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(s=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=E,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${D(n)}:${D(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>D(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new E(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function O(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?s.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(O(e,t),l.dayMs)},t.diffMillis=O,t.closeTo=function(e,t,i){return(0,u.mapOr)(O(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(r+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=s.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},s=(0,M.normalizeZone)(t);if(null!=e&&null!=s&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(s,r):k(e)?.setZone(s,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,T.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),D=i(50140),E=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:A.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return A.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return A.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=O({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,E.isDateTime)(i)?i:(0,D.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function O({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of A.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=O;class A{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=O({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=A,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},A.instance=(0,u.lazy)((()=>new A));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),s=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),s=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),s=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),s=i(59694),n=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,D=/[-โˆ’]/,E=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=D.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,E,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,O=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function A(e){return F(O().exec(e))}t.ianaZoneToOffsetMinutes=A,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=A(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function D(e){if(null==e)return!1;const t=k(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return D(e)?e:void 0},t.isValidDate=D;const E=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===E)return E;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof s.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=s.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return D(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function O(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function A(e,t,i){return(0,u.gt0)(i)&&s.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||O(t,e))&&(!(0,u.gt0)(i)||A(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=O,t.validDay=A,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),s=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),s=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),s=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),s=i(7162),n=i(61253),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),s=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),s=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),s=i(19658),n=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(s.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),s=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,s.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let s;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();s=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:s});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),s=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),s=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),s=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),s=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},34879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(20681),s=i(69317),n=i(22143),a=i(53719),o=i(85890);t.sqliteVersion_=(0,r.lazyAsync)({later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),s=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),D=i(10156),E=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+E(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+E()),preexistingDir:i});return e}}function x(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+E(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),s=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(14889),o=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),s=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),s=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),s=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),s=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),s=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},96416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(4866),s=i(39938),n=i(87748),a=i(17078),o=i(7162),l=i(62936),u=i(10408),c=i(95725),d=i(76531),h=i(82041),f=i(82341),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),s=i(82798),n=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),s=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),s=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!s.isProd&&!(0,n.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),s=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(87561)),n=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(s.default.readFileSync(r)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(n))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),s=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),s=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),s=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),s=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),s=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,s.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),s=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),s=i(87489);function n(e,...t){return s.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,r.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),s.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),s=i(4866),n=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,s.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let s=!1;t.isSyncing=function(){return s},t.setIsSyncing=function(e){s!==e&&(s=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),s=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,s.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,s.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),D=i(43383),E=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),O=i(75556),A=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),se=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,O.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,O.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),s=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=s,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let s=!1;if((0,P.isEmpty)(i))return;const n=be((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),s||(s=p(this,r,"m",f).call(this,e));s&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,O.gt)((0,H.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,E.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,A.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},s=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?s.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(s.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,s),this.save(),s)}}t.SharedState=Se,s=Se,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),b.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:s}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(s)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,D.defer)((()=>{ce.Settings.libraryDir.watchLater(p(s,s,"f",u)),ce.Settings.cacheDir.watchLater(p(s,s,"f",u)),ce.Settings.sharedStateDir.watchLater(p(s,s,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,se.nativePathsEqlSync)(e,s.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(s.instance()),s.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(s,s,"f",l).call(s);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new s(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),s=i(79015);let n=!1;(0,r.later)((()=>(0,s.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(87561)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),s=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),D=i(88491),E=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),O=i(98510),A=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),se=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const s=(0,he.resolve)(i),n=new Se(s,t);return be().set(i,n),be().set(s,n),n}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,E.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,A.pad2)(t+1),(0,A.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,D.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,D.unixtime)(t)>=(0,D.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,D.unixtime)(t)>(0,D.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,O.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*D.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:D.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*D.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),s=i(17310),n=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),s=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),s=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),s=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,s.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const s=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(s);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(s,(async(e,i)=>{g().trace("callback",{nativePath:s,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:s}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(s,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,s.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),D=i(20902),E=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),O=i(98462),A=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:O.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?E.LogLevels.debug:E.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,D.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:se,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,S.thenNot)((0,A.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),b=i(77696),S=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,s.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,r,"m",a).call(this)}),o(this,s,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,s=new WeakMap,r=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,b.fmtFullDuration)(this.staleMs," ")});const i=await l(this,r,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,S.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,s,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),s=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,s.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),s=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,s.pick)(await(0,r.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),s=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(66776),s=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),_=i(92332),T=i(11944),D=i(37609),E=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),O=i(20636),A=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,s,Math.max(Date.now(),w(this,s,"f",n)+1),"f",n),(0,T.compactBlanks)([H.TokenRadix.encode(w(this,s,"f",n)),N.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return w(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=s,s,(i=w(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(s,s,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:E.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(s,s,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+E.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),s=i(44726),n=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),D=i(79015),E=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),O=i(95725),A=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,E.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,E.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,O.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,s,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,s,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,s,"f")});const e=c(this,s,"f"),i=await(0,A.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,s,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,D.ee)().emit("fileChanged",this.targetNativePath),u(this,s,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,O.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,s,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,s,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),s=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44470)),n=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(6005)),n=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),s=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),s=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),s=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),s=i(44726),n=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),s=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return D(e,i,t);const r=await Promise.race([T(e,t),E(e,t)]);return t.halt(),r}(t.nativePath)))}async function T(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function D(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function E(e,t){const i=await(0,m.readdir)(e);return null!=i&&D(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function E(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(g.isLinux?r===s:(0,m.equalsIgnoreCase)(r,s))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=E,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=x(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),F([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("โ€ฆ"),F([...s,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await s.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>E({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),D=i(61570),E=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),O=i(14889),A=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),se=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:O.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,A.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,A.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,A.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,A.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,D.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,A.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,A.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,E.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:O.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(O.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(O.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,A.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function D(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function E(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function O(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function A(e){return[...O(e),{notMissingMimeType:D},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:E},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??A(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=O,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...O(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...O(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...O(e))},t.expensiveFileFiltersFor=A,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>s.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(s.default.join((0,t.execDir)(),"resources"),s.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=s.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),s=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),s=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),s=i(51081);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(s===h.Timeout&&(0,p.onTimeout)({soft:!1}),s!==h.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):D(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=D},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const s=r(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return s.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),s=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),s=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const s=r(i(87561)),n=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(P(r),P(s));if(null==n||n>1)return"unmatched "+i+": "+r+" โ‰  "+s}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const s=r(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),s=i(6314);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),D=i(91641),E=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),O=i(18849),A=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const H=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function q(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return q().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,s,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=q,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return q().descendants((async e=>(0,A.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends E.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),D.EndableRanks.service),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,s,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,O.stack)()});{this.logger.log(H.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),s={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([s],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return l(this,n,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,s,"f")}}t.SyncReport=$,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,s,function(){const e=c.DateTime.now();return q().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,s,"f").nativePath),this.logger.info("Opening new report: "+l(this,s,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,s,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,s,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),s=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),s=i(14889),n=i(95725);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),s=i(34996);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},81286:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(10408),a=i(96593),o=i(83135),l=i(79403);t.exiftoolHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifToolโ€ฆ",settings:[],later:async()=>{try{const e=await(0,a.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,o.ver)(e),(0,r.tt)((0,a.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}catch(e){return{level:"error",msg:"Something's amiss with ExifTool: "+(0,n.errorToS)(e)}}}})))},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(93977),o=n(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},2882:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(43383),s=i(15203),n=i(13699),a=i(79403);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directoriesโ€ฆ",settings:[],later:n.externalDirectoryCheck})))},44606:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const s=r(i(52167)),n=i(43383),a=i(43947),o=i(77125),l=i(7162),u=i(55568),c=i(14889),d=i(20681),h=i(43414),f=i(19209),m=i(36297),p=i(79403),g=(0,n.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({later:async()=>{try{if(!(0,u.isWebService)()){const e=f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}).toString(),t=await s.default.get(e,{timeout:c.ShortCommandTimeoutMs}),{status:i,data:r}=t;if(m.HttpStatusIs.ok(i)&&(0,o.isHealthCheckSummary)(r))return r.libraryDir!==(h.Settings.libraryDir.valueOrDefault??null)?void g().error("getHealthSummary(): libraryDir mismatch",{local:h.Settings.libraryDir.valueOrDefault,remote:r.libraryDir}):(g().debug("getHealthSummary()",{url:e,status:i,data:r}),r);g().warn("getHealthSummary(): invalid response",{url:e,status:i,data:r})}}catch(e){g().warn("Failed to get health check summary from web service",{error:e})}},ttlMs:c.ShortCommandTimeoutMs}),t.getLocalHealthSummary=(0,d.lazyAsync)({later:()=>p.HealthCheck.awaitSettled(),ttlMs:c.ShortCommandTimeoutMs}),(0,a.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},79403:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),D=i(66776),E=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),O=i(13779),A=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),Z=i(18295),X=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,s,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,s,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,s,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,s,"f",l).toA()}static addLoadingMsg(e){v(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,s,"f",h).entriesByCountDesc()}),(0,D.map)((0,O.leastBy)(e,(e=>[v(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,D.map)(e,(e=>v(this,s,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return v(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=s.summary();if(t.settledCountv(s,s,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>s.onResultChange(),onError:()=>s.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,O.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,s=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,s,"f",n),(e=>!e.isPending)),v(this,s,"f",n)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Z.summarizeHealthChecksSync)({errors:v(this,s,"f",l),skipPending:v(this,s,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,s,!0,"f",u),t.state!==v(this,s,"f",c).last?.state&&v(this,s,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,E.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=s.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,D.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new A.BoundedList(10)},u={value:!1},c={value:new A.BoundedList(10)},d={value:new A.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(s,s,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(s,s,"m",m).call(s))),Q.resetDebounced=(0,N.debounce)((()=>s.reset()),50)},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),s=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},46747:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(4866),s=i(36535),n=i(43383),a=i(77125),o=i(7162),l=i(19658),u=i(29405),c=i(79015),d=i(82041),h=i(81286),f=i(2882),m=i(79403),p=i(61099),g=i(71664),y=i(28482),v=i(22627),w=i(32940),b=i(17938),S=i(40715),P=i(11560),M=i(44454),_=i(93763),T=i(97596),D=i(74113),E=i(23119),k=i(59415),x=i(20610),C=i(9335),F=i(12358),I=i(84729),O=i(42386),A=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test checkโ€ฆ",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,D.settingsEnvHealthCheck)(),(0,k.settingsSystemHealthCheck)(),(0,E.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,M.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,_.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,I.videoHealthCheck)(),(0,O.volumeHealthCheck)(),(0,F.versionHealthCheck)(),l.isProd||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(A().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{A().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},61099:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(71923),u=i(15203),c=i(83135),d=i(79403);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC toolingโ€ฆ",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},71664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(66776),a=i(10408),o=i(22143),l=i(15299),u=i(49849),c=i(83135),d=i(79403);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"โ€ฆ",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK","jpegtran is a supported version.",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),s=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},28482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(24586),l=i(82341),u=i(10408),c=i(3955),d=i(15203),h=i(51053),f=i(43414),m=i(82041),p=i(32421),g=i(79403),y=i(91499);async function v(){const e=await(0,l.setupLibraryDirs_)();return(0,m.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}async function w(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(f.Settings.libraryDir.toEnvLine(f.Settings.libraryDir.defaultValue))}`]};const t=await(0,p.mountpoints_)(),i=(0,c.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[y.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`];return null!=t&&(0,a.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}return await v()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}.`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}}async function b(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:"No PhotoStructure library is open"};if(!(0,m.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",f.Settings.libraryDir.hasValue()?(0,r.tt)(f.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await v():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}t.libraryDirectoriesCheck=(0,n.defer)((()=>g.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directoriesโ€ฆ",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,d.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:(0,d.isDocker)()?w:b})))},22627:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(75556),l=i(61570),u=i(17078),c=i(82341),d=i(42648),h=i(43414),f=i(46573),m=i(79403);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)โ€ฆ",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},17938:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(97742)),n=i(36535),a=i(43383),o=i(46954),l=i(83135),u=i(79403);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.jsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},40715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(43383),s=i(27175),n=i(51053),a=i(79403);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directoryโ€ฆ",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},11560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(43383),s=i(55463),n=i(79403);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating systemโ€ฆ",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},44454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(10408),a=i(51053),o=i(71663),l=i(83135),u=i(79403);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShellโ€ฆ",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},93763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(34879),a=i(10408),o=i(83135),l=i(79403);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLiteโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},97596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(75556),o=i(24586),l=i(42648),u=i(29405),c=i(60052),d=i(51053),h=i(79403);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission levelโ€ฆ",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},74113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(17078),a=i(43414),o=i(77016),l=i(79403);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},23119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(43383),s=i(82041),n=i(79403),a=i(59415);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settingsโ€ฆ",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},59415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(17078),o=i(91464),l=i(10408),u=i(98250),c=i(82041),d=i(98024),h=i(79403);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},20610:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=t.sharpHealthCheck=void 0;const s=r(i(39084)),n=i(71017),a=r(i(57441)),o=i(43383),l=i(24603),u=i(87748),c=i(61570),d=i(10408),h=i(27175),f=i(79403);async function m(e){const t=e??(0,n.join)(h.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(t,{failOn:"error"}),r=await i.resize(31,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,l.eql)((0,c.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:31,height:32,channels:3}),"Unexpected sharp output: "+(0,u.stringify)(r.info))}t.sharpHealthCheck=(0,o.defer)((()=>f.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharpโ€ฆ",settings:[],later:async()=>{try{return await m(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,d.errorToS)(e)]}}}}))),t.testSharp_=m},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),s=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},9335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(43414),l=i(11053),u=i(79403);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system loadโ€ฆ",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},12358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(57310),a=i(79403);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure versionโ€ฆ",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},84729:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(46517),u=i(15203),c=i(83135),d=i(79403);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video toolingโ€ฆ",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},42386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(20636),l=i(17078),u=i(13779),c=i(14889),d=i(51053),h=i(7903),f=i(69551),m=i(53719),p=i(46573),g=i(79403);t.volumeHealthCheck=(0,a.defer)((()=>g.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumesโ€ฆ",settings:[],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:d.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,p.volumes)(),(0,m.commandTimeoutMs)());if(i===o.Timeout){const i=await(0,o.thenOrTimeout)(d.isWin?(0,f.getLocalVolumesWin_)():(0,h.dfPosixRawLocal_)(),c.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===o.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following mountpoints:",(0,s.li)(a.map((e=>e.mountpoint)))]};const[g,y]=(0,u.partition)(i,(e=>!0===e.remote));return{level:"ok",msg:["Volumes seem OK",(0,l.plur)(y.length,"local volume")+" and "+(0,l.plur)(g.length,"remote volume")+" checked."]}}})))},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),D=i(43414),E=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),O=i(14489),A=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,s.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const s=i.sha??await r.sha();if(null!=s)if(!0!==await(0,t.isBadSha)(s))try{return await this._build(r,i)}catch(t){e.push(t),L().set(s,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,A.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:a,height:o,sha:l,mimetype:u}=t;if(null==s||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(r,s);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&D.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=D.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),s=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),s=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),s=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),s=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),s=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),D=i(68107),E=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function O(e){const t=w.PosixFile.for(e),i=await(0,D.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?E.dctHash:E.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function A(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:O}),t._imageHash_=O,t.isImageHash=A,t.toImageHash=function(e){if(null!=e){if(A(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(A(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),b=i(60346),S=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),D=i(72461),E=i(36143),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,D.isImageHash)(e.a)&&(0,D.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=D.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function I({a:e,b:t,greyscale:i,dim:r=D.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function O(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,D.imageHash)(e),await(0,D.imageHash)(t),r)})}function A(e,t,i={}){const r=(0,D.toImageHash)(e),s=(0,D.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=I({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=I({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),O=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),A=[];P&&A.push(`aspect ratio mismatch (${(0,E.fmtAspectRatio)(v)} vs ${(0,E.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&A.push("different image content ("+(0,l.andList)(L)+")");const j=g>=O,z=j&&N.avg>=F;j||A.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:O,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(A)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return A(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=D.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=I,t.isSimilarImage=O,t.compareImageHashes=A,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return O(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(A(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(A(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),s=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),s=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),s=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(889),n=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),D=i(84685),E=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),O=i(49312),A=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const n=await(0,E.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),A=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,D.orientationRequiresMirroring)(a.orientation);if(!0===i||g||A||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:A,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=s.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*s.secondMs},p1:{x:20*o.MB,y:12*s.secondMs}},p={p0:{x:11*o.MB,y:12*s.secondMs},p1:{x:26*o.MB,y:24*s.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,s=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+s+n+c+d),dbMs:i,tagMs:s,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),s=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),s=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),D=i(49586),E=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),O=i(68107),A=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),s=E.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??E.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:E.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:E.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,O.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,L.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,E.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,A.commandTimeoutMs)()}),s.nativePath}async function q(){return E.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,E.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const r=j("transcode",e),s=$.get(t.nativePath);if(null!=s&&!(0,n.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:s.name}),s.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),s=(0,x.extractDurationSec)(r),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,s={src:e,...V(e,d)},n=J(o,s.videoBitrateKbps,i),a=E.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(s.width=(0,u.roundEven)(e.width),s.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));s.dest=i,s.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(s));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function D(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=D;const E=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await D();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await D(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await D(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...O(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await D(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),s=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,s.lazy)((()=>(0,r.toGt0)(n.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),s=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const D=["-T"],E=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...D,...E,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),O=[];function A(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});O.push(r)}}I.on("error",A),I.stderr.on("data",A);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,s.isNotEmpty)(O))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:O,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),s=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),s=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),D=i(43414),E=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,E.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function A(e,i,r,s){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await O(e),sids:null!=s?s:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=A,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await A(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),r=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(D.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,s.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),s=i(4866),n=i(39938),a=i(10508);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),D=i(10508),E=i(73435);t.k=(0,a.defer)((()=>(0,D.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,E.toUID)(E.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function O(){return P.isLinux?(await I("lm")).map((e=>(0,E.toUID)(E.S.lm,e))):void 0}async function A(){return P.isLinux?(await I("lp")).map((e=>(0,E.toUID)(E.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,E.toUID)(E.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,E.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,E.toUID)(E.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,E.toUID)(E.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,E.toUID)(E.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,E.toUID)(E.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,E.toUID)(E.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,E.toUID)(E.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,E.toUID)(E.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,O,A,L,B,U,H],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return k().tap({msg:"sids()",result:(0,E.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)q.add(t)},t.clearSids=function(){f.isTest&&q.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),s=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),s=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),s=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),s=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),s=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(4866),s=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),s=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),s=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>s(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),s=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,s.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),s=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),s=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),D=i(3955),E=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),O=i(98968),A=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,E.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,D.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,O.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,O.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,D.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,O.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,O.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,A.readLogEntries)(e,{start:r,end:i}),(e=>(0,O.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),s=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),D=i(83837),E=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),O=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class A extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,s,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,O.recentLogEntries)()),(0,O.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=A,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,D.endStream)(e.stream),E.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),s=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),s=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),s=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,s.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const s=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&s.push(y.ConsoleLogger.instance()),(0,n.map)((0,b.logBroadcaster)(),(e=>s.push(e))),l.rootLoggers.set(s),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),D(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,s.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const D=(0,s.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},60346:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,s=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),s=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),s=i(89965);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),s=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),s=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),s=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),s=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),s=i(3331);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),s=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),s=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),s=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),s=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),s=i(4866),n=i(82798);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),s=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),s=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),s=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),s=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),s=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),s=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),D="{ready}",E=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${D}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:D,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,E),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,E),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),s=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),s=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),s=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,s.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,s.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),s=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){D(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&E()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(g.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function D(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function E(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=D,t.disableExternalNetworkRequests=E},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),s=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),s=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),s=i(63774);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),s=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,s.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,s.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,s.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,s.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),s=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),D=i(7560),E=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),O=i(51053),A=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),se=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>O.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!O.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>O.isMac?"100ms":O.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:O.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,A.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>O.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,E.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,A.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(O.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:se.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(s.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(s.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),s=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>s.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:s.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),D=i(98462),E=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),O=i(95699),A=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(A.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(D.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function H(e){return(0,m.map)(z(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",q),(0,T.ee)().on("settingsChanged",q),I.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await D.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(s),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"old"}),await s.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Z(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(E.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(E.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),s=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),s=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),s=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),s=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),s=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),s=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},77016:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(61570),s=i(91464),n=i(29405),a=i(60052),o=i(43414);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a)null==a.value.opts.fromEnv(r)&&i.push({envKey:n,msg:`The value "${e[n]}" isn't valid for this ${a.value.constructor.name}.`});else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),s=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),s=i(91464);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),D=i(54809),E=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),O=i(43414),A=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,E.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],s=r;if((0,E.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(s))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,E.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",U(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??s("tags",U(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:s("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",q(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),s=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(889),n=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),D=i(21084),E=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),O=i(2023),A=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),Z=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),se=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,A.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new D.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new D.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=E.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,X.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,O.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,O.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,Z.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,Z.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=E.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,O.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=E.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function D(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return D({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=D,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),s=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),s=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),s=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),D=i(96593);function E(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=E,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function O(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,D._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,D.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const s=E(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),O(i,s,n)},t.ensureHistoryRecords=O},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,l.toDated)(t[r]);if(null==s||(0,h.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),s=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),s=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},65308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(66776),l=i(11254),u=i(39784),c=i(7162),d=i(1058),h=i(91464),f=i(6667),m=i(43414),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Zโ€˜โ€™']+[-A-Zโ€˜โ€™']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function M(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(M(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,D=b.length;if(_.length>0)if(0===T&&D>0)l.push(..._);else if(0===D&&T>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function M(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),r=M(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),s=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),s=i(75556),n=i(43414);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),s=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(r.length)),l=n(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),s=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),D=i(75123),E=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),O=i(96593),A=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,D.isSlowDir)(e.nativePath)&&!await(0,D.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,O.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(A.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),s=(0,E.findFileIndex)(e,r);if(s<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,O.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),s=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),s=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(s,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return D(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?D(this,!0):(null==this._formatted&&(this._formatted=D(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function D(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function E(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+E(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>E(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),s=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),s=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),s=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),s=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},33611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(4586),s=i(98250);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),s=i(39036);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),s=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},73037:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(82798),s=i(13779),n=i(49849),a=i(39036);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},17953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(61570),s=i(44726),n=i(39036);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},83135:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(39938);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},57310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.systemUserAgent=t.userAgent=t.checkVersion_=t.currentChannel=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(19067),l=i(9678),u=i(54883),c=i(7162),d=i(55463),h=i(14889),f=i(42041),m=i(20681),p=i(4586),g=i(76531),y=i(69060),v=i(43414),w=i(53719),b=i(15425),S=i(33611),P=i(38846),M=i(73037),_=i(17953),T=i(39036),D=i(83135),E=(0,a.defer)((()=>(0,c.mkLogger)("VersionCheck")));async function k(){return v.Settings.allowUserAgent.valueOrDefault?x():l.SimpleAppName}async function x(){return l.SimpleAppName+"/"+f.version+" ("+(0,d.osFullName)()+") "+(0,u.EditionType)().toLowerCase()+"/"+await(0,y.t)()}t.currentChannel=function(){const e=[v.Settings.updateChannel.valueOrDefault,(0,P.channel)()].map((e=>T.UpdateChannels.ordinal(e))).sort()[0];return T.UpdateChannels.values[e]??v.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(!v.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===v.Settings.optOut.value?e.push("Set "+(0,s.tt)(v.Settings.optOut.toEnvLine(!1))+" to enable."):!1===v.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,p.configDir)();if(null==i||!await(0,g.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const l=e?.installedVersion??f.version,c=(0,T.extractUpdateChannel)(l),d=(0,T.eligibleForChannel)(c),h=a.versions.filter((e=>d.includes(e.channel))).map((e=>e.version)),m=e?.latestVersion??(0,M.semverLatest)(...h);if(null==m)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+v.Settings.updateChannel.toEnvLine()]};const y=(0,T.extractUpdateChannel)(m),w="You are running "+(0,u.EditionName)()+" "+(0,D.ver)(l),b="The latest published "+(0,s.tt)(y)+" build is "+(0,D.ver)(m),S=y===c?void 0:"You should consider switching to the "+(0,s.tt)(y)+" channel.",P=Date.now()-a.updatedAt,_="Last checked "+(P{const e=(0,S.channelVersionsCache)(),i=await(0,b.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",config:{headers:{"User-Agent":await k()},timeout:h.ShortCommandTimeoutMs},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:f.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,_.isUpdateChannelVersion)(e)))||r.updatedByVersion!==f.version){if(i.fromCache)return E().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();E().throw("getChannelVersions_(): Invalid response",{result:r})}return E().tap({msg:"getChannelVersions_()",result:r})}})},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),s=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),s=i(55412),n=i(46573);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),s=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await O()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function D(e){return(0,l.map)(T(e),(e=>e+":\\"))}function E(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=D,t.getPsDriveCommand=E,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=D(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function O(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(D)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(E(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(I)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=O},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),D=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,D.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const E=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?E().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):E().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(E().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,D.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void E().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,D.mountpointsTtlMs)(),(()=>E().warn("gioVolumes(): timed out after "+D.mountpointsTtlMs+"ms")),(e=>E().log((0,s.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,D.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void E().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),s=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),s=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),D=i(43414),E=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),O=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function A(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){A(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{D.Settings.libraryDir.watchLater(A),D.Settings.scanPaths.watchLater(A),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=D.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||D.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),A()})),D.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=M,t=_,i=T){if(g.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),s=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),s=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function E(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>E(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=D,t.readVolumeUUID=E},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),D=i(91464),E=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),O=i(20902),A=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),se=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=s.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){se().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,D.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:ne}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){se().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));se().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return se().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const s=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return se().debug("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return se().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function ge(e,t,i){const r=i.filter((e=>(0,D.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,D.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,U.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,D.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return se().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return se().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,A.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return se().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(se().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void se().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,A.onError)("Timed out getting local volume metadata")));if(null==e)return void se().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;se().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){se().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,A.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return se().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,D.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(se().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},15425:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const s=r(i(52167)),n=i(43383),a=i(75556),o=i(7162),l=i(14889),u=i(36297),c=(0,n.defer)((()=>(0,o.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,a.gt0)(await t.size())&&(0,a.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await s.default.get(e.url,{timeout:l.ShortCommandTimeoutMs,...e.config}),n=r.data;u.HttpStatusIs.success(r.status)||c().throw("Failed",{url:e.url,response:r});const o=e.preCacheTransform?.(n)??n;return c().info("Fetch success. Caching",{args:e,json:o,cache:t}),await t.writeJson_(o),{data:o,updatedAt:Date.now(),fromCache:!1}}},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),s=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),s=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),s=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.availableCpus=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),b=i(91641),S=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),D=i(59387),E=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{E().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)},t.availableCpus=function(){if(_.Settings.cpuBusyPercent.valueOrDefault<=0)return;const e=x.instance().idlePct();if(null==e)return;const t=Math.floor((0,T.cpuInfo)().length*(_.Settings.cpuBusyPercent.valueOrDefault/100));return Math.floor(t*(e/100))};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:b.EndableRanks.first}),r.add(this),s.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??F()}}t.CpuUsage=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,F());const e=new C;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?Math.round(t/r*100):void E().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+S.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let s=!1;function n(){s&&(s=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return s},t.pause=function(e=!0){!1===e?n():s||(s=!0,(0,r.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),s=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),s.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),s=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),s=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),s=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),s=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),s=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),s=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),s=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),s=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),s=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),s=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),s=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,s.isFunction)(e)&&(0,s.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),s=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),s=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),s=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),s=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=s.length;(0,r.filterInPlace)(s,(t=>e(i,t))),t=t||n!==s.length,0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),s=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,s){return!(null==s||!l(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,s.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function D(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=D,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return D(0,100,b(t)?_(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),s=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),s=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),s=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),s=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),s=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),s=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),s=i(61570),n=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{r&&(0,s.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,s=!0){const n=await o(e,i,s);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const s=i-Date.now();return s<=0?t.Timeout:o(e,s,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return l(e,s,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:s=!0}){const a=await o(e,i,s);return a===t.Timeout?(0,n.tot)(r):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),s=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),s=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),s=i(82798);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),s=i(75556);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),s=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),s=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),s=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),s=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const r=i(4866),s=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),b=i(43414),S=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),D=i(94332),E=i(63216),k=(0,r.lazy)((()=>(0,s.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,E.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,r.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:b.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,r.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:b.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,r.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(b.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,r.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),O=(0,r.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),A=(0,r.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(b.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,r.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,D.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,D.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:b.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,S.compact)([x(),C(),F(),I(),O(),(0,w.LogDirCleanup)(),A(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},49374:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),D=i(46573),E=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),O=i(61570),A=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,D.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,O.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>A.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,E.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,E.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,n=new WeakMap,s={value:void 0}},93445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(23872),s=i(31216),n=i(9069),a=i(13222);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},13902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(4866),s=i(7162),n=i(80294),a=i(82341),o=i(43414),l=i(82041),u=i(53719),c=i(46573),d=i(88491),h=i(75556),f=i(17078),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.available{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),s=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,s.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),s=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(s.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+s),s):s}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i(0,l.mkLogger)("library.SuggestedLibraryDir")));class I{static async for(e,t){if((0,k.blank)(e))return;const i=await(0,T.bestVolumeForPath)(e,t);if(null==i)return void F().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,m.isLibraryDir)(e);return new I(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=_.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=_.Settings.minDiskFreeGb.valueOrDefault*C.GB){if(this.isLibrary)return;const t=await(0,P.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,b.containsHiddenPathname)(this.nativePath))return F().tap({...i,result:"contains hidden path"});{const e=await(0,w.whyExcludedDirectoryRecursive)(v.BaseFile.for(this.nativePath));if(null!=e)return F().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,y.canRWXFirstExistingAncestor)(this.nativePath)?(0,x.gt0)(e)&&this.availableBytesnew I(e,!1,{mountpoint:"/test",available:C.GB})))});const l=[],d=[],y=await i??await(0,T.volumes)();if(null==y||(0,D.isEmpty)(y))return F().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await I.for(t,y);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(F().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(_.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,p.picturesDir)());const w=[n.default.cwd(),...await(0,S.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,S.childDirectories_)((0,f.homeDir)())),(0,D.filterInPlace)(w,(e=>(0,b.isNotHiddenPosixPath)(e)));for(const e of w)await(0,m.isLibraryDir)(e)&&(F().info("current working dir is a library",e),await v(e));function P(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(F().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,f.homeDir)(),(0,a.AppName)())),await(0,h.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:y,f:e=>async function(e){try{if(await(0,m.isLibraryDir)(e.mountpoint))return F().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,S.childDirectories_)(e.mountpoint)){if(P())break;if(await(0,m.isLibraryDir)(t))F().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,S.childDirectories_)(t)){if(P())break;await(0,m.isLibraryDir)(i)&&(F().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());F().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){F().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),F().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const k=l;for(const e of(0,E.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(k.length>=t)break;k.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(F().debug("adding new path",e),k.push(e))}return(0,D.uniqBy)((0,E.sortBy)(k,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=I,t.suggestedLibraryDirs=(0,o.lazy)((()=>O())),t._suggestedLibraryDirs=O},98505:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(45161),s=i(35796),n=i(54883),a=i(79403),o=i(69060),l=i(95976),u=i(55463),c=i(33407),d=i(55568),h=i(43414),f=i(82041),m=i(45113),p=i(24586),g=i(42041),y=i(11053),v=i(59387),w=i(11944),b=i(39938),S=i(38625),P=i(19067),M=i(66776),_=i(75556),T=i(26588),D=i(44726),E=i(17078),k=i(30690),x=i(89452),C=i(50725);async function F(){if(null==k.Asset.db())return;const e=[];e.push((0,E.plurMetric)(k.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,D.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,E.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,E.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const I={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:I[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,M.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,M.map)(y.CpuUsage.instance().busyPct(),(e=>(0,_.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,_.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),s=i(85297),n=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},24709:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(91464),o=i(93125),l=i(43414),u=i(96593),c=i(28033),d=i(61473),h=i(11944),f=i(39938),m=i(61570),p=i(11254),g=i(82798),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},69258:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(43414),o=i(61473),l=i(11944),u=i(26588),c=i(30690),d=i(24709),h=i(51832),f=i(18290),m=i(96672),p=i(82355),g=i(7587),y=i(52465),v=i(40399),w=i(83089),b=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function S({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];t.some((t=>t.nativePath===e.nativePath))||t.unshift(e),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{b().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,g.lensTagFile)(e),(t=>{b().debug("Lens tag for "+e+":",t),u.push(t)})),await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{b().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,w.whoTagFiles)(t)??[];b().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,p.keywordTagFiles)(t,c),(t=>{b().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{b().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{b().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{b().debug("Album tags for "+e+":",t),u.push(...t)}));const S=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(y.normalizeTagRoot),o.joinTagPath)),P=await(0,y.tagDeltas)(i,S);return b().info("tagAsset("+e+")",{priorTagPaths:i,after:S,result:P}),P}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();b().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void b().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(b().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await S({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});b().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return b().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),b().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});b().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=S},51832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(96593),s=i(11254),n=i(11944),a=i(39938);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),s=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},96672:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(4866),s=i(7162),n=i(61473),a=i(22356),o=i(11944),l=i(49049),u=i(11254),c=i(89452),d=i(9069),h=i(63216),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},82355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(1058),o=i(91464),l=i(2073),u=i(46852),c=i(43414),d=i(96593),h=i(28033),f=i(61473),m=i(11944),p=i(59694),g=i(39938),y=i(43947),v=i(1429),w=i(66776),b=i(11254),S=i(82798),P=i(52465),M=i(83089),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function D(e){return _().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function E(e){return[...D(e.parent().posixPath),...D(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=D,t.extractPathnameTags=E;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(k,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,s]=(0,r.partition)(x(e),M.isWhoTag),n=(0,v.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(E)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},7587:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(46852),s=i(43414),n=i(96593),a=i(11254),o=i(11944),l=i(39938),u=i(66776);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),s=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},40399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(46852),o=i(15465),l=i(11944),u=i(39938),c=i(66776),d=i(90957),h=i(11254),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():(0,c.orElse)(m.get(e.trim().toLowerCase()),(()=>(0,n.capitalize)(e)))}t.friendlySubtype=y,t.fixCase=v},83089:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(4866),s=i(7162),n=i(43414),a=i(96593),o=i(71932),l=i(65308),u=i(61473),c=i(11944),d=i(39938),h=i(1429),f=i(61570),m=i(11254),p=i(39784),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},18130:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),D=i(88491),E=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class O extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=D.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*D.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),s=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:s,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,E.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,y.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=O,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,E.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),D=i(94332),E=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,E.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,E.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,D.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),s=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function D(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function E(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=D,t.fsLockForDb=E,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=D(e);return{...t,fslock:E(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),s=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,s.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},13915:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeSchemaJsonFile_=t.assertValidDbSchema_=t.schemaJsonFile=void 0;const s=r(i(49411)),n=i(13779),a=i(4866),o=i(7162),l=i(98250),u=i(27175),c=i(11944),d=i(51367),h=i(17078),f=i(91796),m=i(51603),p=(0,a.lazy)((()=>(0,o.mkLogger)("db.DbSchemaValid")));function g(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=g,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,m.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await g(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&p().throw("Db is missing "+(0,h.plur)(t.length,"table")+" : "+(0,d.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)p().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&(p().error("Missing columns",{expected:t,actual:e}),p().throw("Db is missing "+(0,h.plur)(i.length,"column")+" from table "+e.tableName+" : "+(0,d.andList)(i.map((e=>e.name)))))}}p().info("Validated schema.")}catch(e){throw(0,f.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return g(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,m.localTableInfo)(t)},{spaces:2})}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),s=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),D=i(43947),E=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),O=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,E.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(I.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,D.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,O.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),D=i(85476),E=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())E().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:D.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,D.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();E().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,D.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));E().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),s=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),D=i(6314),E=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),O=i(9069),A=i(70582),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,A.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,E.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,O.modelDb)()?.end()),await(0,A.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,E.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},s),o=new D.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),s=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),s=i(89253);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),s=i(43414),n=i(82798);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},91796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(42648),s=i(10408),n=i(79403),a=i(82041),o=i(36535),l=i(88491),u=i(43383),c=i(49374),d=i(13915),h=i(91894),f=i(77910),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library databaseโ€ฆ",settings:["libraryDir","forceLocalDbReplica"],ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{if(!(0,a.libraryHasSettings)())return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let e,t,i=!1;try{const s=Date.now();if(i=!1,t=c.Library.instanceRequired(),(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(await t.ready,e=await t.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(e),i=!0,await e.verify_(),await e.vacuum(),f.Heartbeat.assertPing_();const n=await t.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(e.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==e?void 0:"Live db is "+(0,o.tt)(e.dbFile.nativePath),null==t?void 0:"Local replica mode is "+(0,o.tt)(await t.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},39946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(4866),s=i(46747),n=i(82041),a=i(91796),o=i(23134),l=i(53829);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},23134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(13779),s=i(7162),n=i(98250),a=i(23872),o=i(79403),l=i(82041),u=i(11944),c=i(36535),d=i(43383),h=i(71766),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directoriesโ€ฆ",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},53829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(7162),s=i(46852),n=i(79403),a=i(43414),o=i(82041),l=i(47044),u=i(53719),c=i(27127),d=i(46573),h=i(11944),f=i(36535),m=i(43383),p=i(51367),g=i(89253),y=i(61570),v=i(71766),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumesโ€ฆ",settings:["scanAllDrives"],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" โ†’ "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},82118:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const r=i(10408),s=i(48843);process.on("unhandledRejection",(e=>console.error("UNHANDLED REJECTION",(0,r.errorToS)(e)))),process.on("uncaughtException",(e=>console.error("UNCAUGHT EXCEPTION",(0,r.errorToS)(e)))),(0,s.run)()},41634:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InfoArgs=void 0,t.InfoArgs={beforeParse:e=>e.option("--volumes","Emit a table with currently mounted volume metadata. See https://photostructure.com/volumes for details.").option("--mountpoints","Emit a table with currently mountpoints. See https://photostructure.com/volumes for details.").option("--sync-paths","Emit a table listing the paths that will be synced next.").option("--plan, --licensing","Emit plan/licensing information. See the About page in the web UI for more details or to activate a subscription.").option("--child-env","Emit the environment variables provided to all spawned processes.").option("--validate","Only run file validation on the given filenames (requires current PLUS subscription).").option("-j, --json","Emit metadata as un-indented, uncolorized JSON.").option("--load-library","Load the library database so more metadata can be shown (like if a file is currently in your library). This adds a second or two (depending on the size of your library).").option("--filter ",'Case-insensitively filter keys by . may have dots. Note that .nativePath is always included. Repeat to filter for multiple terms ("--filter foo --filter bar").',((e,t)=>t.concat([e])),[]).option("--file-filters","Include an exhaustive list of file and directory filters. This is hundreds of lines long, so it's not included by default.").option("--image-hash",'Automatically filter image hash fields. Equivalent to "--filter imageHash --filter imageHashComparison"').option("--flat","Only return values for objects with only one field").option("--suggested-libraries","Emit the suggested library directories (as seen on the settings page).").option("--volumes-ttl","Emit the volume cache time-to-live (use with --debug to see details).").option("--is-library ","Run a couple quick checks to see if looks like a PhotoStructure library.").option("--read-settings ","Read the given file and output the parsed settings.").option("--recount-all-tags","Recount every asset tag count. This may take a minute or two. Don't have a sync running concurrently. Implies --cleanup.").option("--globs, --exclude-globs","Emit all file and directory exclusion globs.").option("--health","Emit details for all health checks.").option("--doctor","Emit details for all health checks that aren't OK.").option("--skip-health","Disable health checks.").option("--version-check","Check now if the current version is the latest.").option("--table","Emit with console.table() (useful with --volumes or --filter).").option("--cleanup","Run a bunch of maintenance tasks."),afterParse:function(){}}},48843:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.run=void 0;const s=r(i(47261)),n=i(4866),a=i(7162),o=i(2023),l=i(55568),u=i(25516),c=i(63774),d=i(24586),h=i(46080),f=i(67654),m=i(75288),p=i(92356),g=i(2126),y=i(46852),v=i(21142),w=i(10347),b=i(37980),S=i(64063),P=i(9972),M=i(37445),_=i(77696),T=i(62936),D=i(1629),E=i(96416),k=i(82341),x=i(35796),C=i(10408),F=i(17875),I=i(79141),O=i(98462),A=i(64067),L=i(98250),R=i(22143),N=i(44606),B=i(79403),j=i(32148),z=i(31216),V=i(12737),W=i(69060),U=i(4657),H=i(43414),q=i(82041),G=i(98024),$=i(77016),J=i(47044),K=i(33611),Y=i(57310),Z=i(32421),X=i(53719),Q=i(46573),ee=i(11053),te=i(11944),ie=i(39938),re=i(38625),se=i(88491),ne=i(66776),ae=i(61570),oe=i(8199),le=i(7127),ue=i(17078),ce=i(39784),de=i(17146),he=i(49374),fe=i(13902),me=i(4958),pe=i(98505),ge=i(92045),ye=i(39946),ve=i(85223),we=i(41634),be=i(70750);t.run=async function(){try{await async function(){const e=await new b.CLI(le.ServiceNames.info,"[FILE...]",["* Omit any filenames to run diagnostics and output system configuration, tooling, and health check information.","* File paths should be absolute or relative to cwd.","* Provide 2 file paths to see why PhotoStructure may consider them variants of the same asset.","* To emit valid JSON, set NO_COLOR=1 or use --json."].join("\n")).add(we.InfoArgs,M.WriteSettingsArg,ge.LogArgs,S.ColorArgs,P.TimingArg).parse(),t=e.opts(),i=(0,te.uniq)(e.args),r=(0,re.isTrue)(t.flat),g=(0,re.isTrue)(t.table),F=(0,re.isTrue)(t.recountAllTags);F&&(H.Settings.recountAllTags.envValue=!0);const I=F||(0,re.isTrue)(t.cleanup);(0,re.isTrue)(t.imageHash)&&(t.filter??(t.filter=[]),t.filter.push("imageHash"),t.filter.push("imageHashComparison"));const Se=(0,re.isTrue)(t.fileFilters),Pe=(0,n.lazy)((()=>{if((0,te.isEmpty)(t.filter))return;const e=(0,ce.toA)(t.filter);return r&&i.length<=1||e.unshift("nativePath"),2===i.length&&e.push(...e.map((e=>"a."+e)),...e.map((e=>"b."+e))),e}));function Me(e){e=function(e){const t=Pe();return null==t?e:Array.isArray(e)?e.map((e=>(0,ae.pickDeep)(e,...t))):(0,ae.pickDeep)(e,...t)}(e),r&&(e=(0,ae.flattenObject)(e));const i=(0,re.isTrue)(t.json);r&&(0,oe.isPrimitive)(e)?console.log(e):i||(0,re.isFalse)(H.Settings.logColor.value)?console.log(JSON.stringify(e,void 0,i?void 0:2)):g?console.table(e):console.log(s.default.inspect(e,{depth:7,colors:!0,maxArrayLength:1024}))}if((0,u.setServiceName)("info"),(0,re.isTrue)(t.skipHealth)&&B.HealthCheck.disableAll(!0),(0,ie.notBlank)(t.readSettings)){const e=await(0,q.importFileSettings_)(O.BaseFile.for(t.readSettings));return Me({settings:(0,ae.fromEntries)(e.settings.map((e=>[e.name,e.value]))),warnings:e.warnings})}if(await(0,q.readSettings)(),I&&(l.isDbJanitorService.set(!0),H.Settings.logLevel.isUnset()&&(H.Settings.logStdout.envValue=!0,H.Settings.logLevel.envValue="warn",(0,U.setupLogger)())),(0,re.isTrue)(t.versionCheck))return await((0,K.channelVersionsCache)()?.unlink()),H.Settings.autoUpdateCheck.tmpValueIfUnset=!0,Me(await(0,Y.checkVersion_)());if((0,re.isTrue)(t.globs)||(0,re.isTrue)(t.excludeGlobs)){const e=(0,A.excludeGlobs)();return Me({excludeGlobs:{file:e.file.map((e=>(0,ae.pick)(e,"pattern","desc"))),dir:e.dir.map((e=>(0,ae.pick)(e,"pattern","desc")))}})}if((0,re.isTrue)(t.volumes)){const e=await(0,Q.volumes)();if(null!=e)return Me(e.filter((e=>!0!==e.ignorable)).map((e=>({filesystem:e.filesystem,...e,size:(0,ue.fmtBytes)(e.size),used:(0,ue.fmtBytes)(e.used),available:(0,ue.fmtBytes)(e.available),volsha:(0,J.volsha)(e.uuid)}))));console.error("--volumes failed. Please retry with --info for details.")}if((0,re.isTrue)(t.mountpoints)){const e=await(0,Z.mountpoints)();if(null!=e)return Me(e);console.error("--mountpoints failed. Please retry with --info for details.")}if((0,re.isTrue)(t.plan)||(0,re.isTrue)(t.licensing)){const e=(await(0,W.m)())[0],t=(0,ne.map)(e?.l,(t=>({email:t.sub,trial:t.trial,issued_at:t.iat,expires:t.exp,meta:e.meta})));return Me({plan:await(0,W.t)(),current_license:t})}if((0,re.isTrue)(t.suggestedLibraries))return Me(await(0,me.suggestedLibraryDirs)());if((0,re.isTrue)(t.volumesTtl))return Me({volumesTTL:await(0,fe.calcVolumesTTL)()??(0,X.volumeMetadataTtlMs)()});if((0,re.isTrue)(t.childEnv))return Me((0,w.childEnv)());const _e=(0,a.mkLogger)("info");if((0,re.isTrue)(t.loadLibrary)||(0,re.isTrue)(t.syncPaths)||I){const e=(0,k.libraryDataDirPosixFile)();if(null==e)return console.error("Error: please set up your library.");if(!await e.isDirectory())return console.error("Error: your library data dir, "+e+", is missing.");_e.info("Waiting for library to spin up...");const t=he.Library.instance();try{await(t?.ready)}catch(e){_e.warn("Failed to spin up library",e)}const i=(0,T.pathToDb)(e,"models");if(!await i.isNonEmptyFile())return console.error("Error: your library database, "+i+" is missing.")}if(I)return await(0,de.cleanup_)(),Me({cleanup:"OK"});if((0,re.isTrue)(t.syncPaths))return Me(await(0,ve.syncPathsForUI)());if((0,ie.notBlank)(t.isLibrary)){const e=await(0,E.whyNotLibraryDir)(t.isLibrary);return Me((0,ae.compactValues)({isLibrary:null==e,why:e}))}if((0,re.isTrue)(t.validate)){if((0,te.isEmpty)(i))throw new Error("--validate requires filenames");return H.Settings.validateVideos.envValue=!0,H.Settings.validateJpegImages.envValue=!0,H.Settings.validateRawImages.envValue=!0,Me(await Promise.all(i.map((async e=>[e,(0,ie.notBlankOr)(await(0,z.whyInvalidFile)(e),"OK")]))))}if((0,te.isEmpty)(i)){await(0,v.until)((()=>ee.CpuUsage.instance().busyPct()),{timeoutMs:2*se.secondMs,intervalMs:250});const e={systemInfo:(0,ae.fromEntries)((await(0,pe.systemInformation)()).map((({term:e,defn:t})=>[(0,c.asObjectKey)(e),t])))};return e.versionCheck={userAgent:await(0,Y.userAgent)(),...await(0,Y.checkVersion_)().catch((e=>({error:(0,C.errorToS)(e)}))),currentChannel:(0,Y.currentChannel)()},e.user_ids=(0,d.userids)(),e.group_ids=(0,d.groupids)(),e.username=await(0,d.username)(),e.paths={libraryDir:H.Settings.libraryDir.valueOrDefault,originalsDir:(0,k.libraryOriginalsDirPosixFile)()?.nativePath,systemSettingsFile:(0,G.systemSettingsFile)(),librarySettingsFile:(0,q.librarySettingsFile)()?.nativePath,libraryPreviewsDir:(0,k.libraryPreviewsDirPosixFile)()?.nativePath,librarySyncReportsDir:(0,k.librarySyncReportsDir)()?.nativePath,cacheDir:(0,D.cacheDir)(),logDir:(0,x.logDir)(),toolsDir:(0,R.toolsDir)()?.nativePath,osToolsDir:(0,R.osToolsDir)()?.nativePath,ffmpeg:await(0,V.ffmpegNativePath)(),sqlite:await(0,R.sqliteNativePath_)().catch((e=>"not found: "+(0,C.errorToS)(e)))},(0,re.isTrue)(t.health)?(e.healthSummary=await(0,N.getLocalHealthSummary)(),e.healthChecks=await Promise.all(B.HealthCheck.testResults())):(0,re.isTrue)(t.doctor)?(await(0,ye.libraryHealthCheckSetup)(),e.healthChecks=await B.HealthCheck.notOkResults()):e.healthSummary=await(0,N.getRemoteOrLocalHealthSummary)(),e.wrongPsEnvValues=(0,$.verifyPsEnvSettings)(),(0,re.isTrue)(t.loadLibrary)&&(e.libraryMetrics=(0,ae.fromEntries)((await(0,pe.libraryMetrics)())?.map((e=>[(0,c.asObjectKey)(e.desc),e.count]))??[])),e.volumesTTL=(0,_.fmtFullDuration)(await(0,fe.calcVolumesTTL)()),e.nonDefaultSettings=(0,ae.fromEntries)((0,ae.values)(H.Settings).filter((e=>e.hasValue())).map((e=>[e.name,e.humanValue]))),Me(e)}if(2===i.length){const e=L.PosixFile.for(i[0]),t=L.PosixFile.for(i[1]),r=await(0,m.mkAssetFile_)(e),s=await(0,m.mkAssetFile_)(t),n=[];if(null==r&&n.push("Failed to read "+e),null==s&&n.push("Failed to read "+t),(0,te.isNotEmpty)(n))return Me({errors:n});const a=(0,f.whyNotSimilarAssetFile)(r,s),l=null==a?"These two files will be aggregated into a single asset.":"These files represent different assets: "+a;let u,c;if(null==a){const e=(0,p.sortAssetFiles)([r,s]);u=e[0]?.nativePath,c=(0,o.zipPojos)(...await Promise.all(e.map(p.assetFileSortCriteriaPojo)))}const d={fileComparison:l,primary:u,a:await(0,be.info)(e,Se),b:await(0,be.info)(t,Se),cmpArr:c};return H.Settings.useImageHashes.valueOrDefault&&(d.imageHashComparison=(0,ae.omit)((0,j.compareImageHashes)(r,s),"a","b")),Me(d)}{const e=await(0,y.mapAsync)({name:"info",arr:i,f:e=>(0,be.info)(e,Se)}),t=(0,ae.fromEntries)(e?.map(((e,t)=>[t,e])));if(e.length>1){const e=(0,te.compact)(await(0,y.mapAsync)({name:"mkAssetFile",arr:i,f:e=>(0,m.mkAssetFile_)(L.PosixFile.for(e)).catch((t=>{console.error("Failed to read "+e,t)}))})),r=await(0,h.aggregateAssetFiles)(e);t.clusters=r.map((e=>e.map((e=>e.uri))))}return Me(t)}}()}catch(e){(0,F.onError)((0,I.toWrappedError)("Failed",{cause:e,fatal:!0}))}finally{await(0,g.exit)({reason:"done",status:0})}}},70750:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.info=void 0;const r=i(2023),s=i(75288),n=i(92356),a=i(4132),o=i(10408),l=i(64067),u=i(25015),c=i(98250),d=i(23872),h=i(95725),f=i(31216),m=i(46517),p=i(38336),g=i(83773),y=i(96593),v=i(27446),w=i(15465),b=i(39938),S=i(88491),P=i(61570),M=i(26588),_=i(49374),T=i(93445),D=i(69258),E=i(89452),k=i(9069),x=i(16630);t.info=async function(e,t){try{const i=c.PosixFile.for(e),o=await(0,w.readMimeType)(i);if(null==o)return{nativePath:i.nativePath,error:`Could not read mimetype for ${i.nativePath}`};if((0,u.isSidecarMimetype)(o))return{nativePath:i.nativePath,mimetype:o,error:"Skipping sidecar mimetype"};if(!await(0,v.isAssetFileMimeType)(i))return{nativePath:i.nativePath,mimetype:o,error:"Skipping non-asset file mimetype"};const h=i.parent(),C=await(0,s.mkAssetFile_)(i),F=t?await p.Predicates.explain(h,...(0,l.notExcludedDirPredicates)(h)):void 0,I=t?await p.Predicates.explain(i,...(0,T.libraryFileFiltersFor)(i,{validateFile:!0})):void 0,O=C.dominantColors?.filter((e=>null!=e?.color?.name)).map((e=>({rgb:e.rgbhex,name:e.color?.name,pct:e.pct}))),A=await(0,D.tagAsset)({primaryVariation:i,files:[],priorTagPaths:[],capturedAts:[],uris:[await i.uri_()]}),L=null==(0,k.modelDb)()?void 0:await new x.AssetFileFinder(i).prior(),R=await(L?.matchesFile()),N=await(0,M.thenCollect)(E.AssetFile.sameShaInLibrary(i),(e=>e.getNativePath())),B=await(0,y.readTags)(i),j=(0,d.whyRejectFile)(i,!0===_.Library.instance()?.isReadySync()?(0,T.libraryFileFiltersFor)(i):void 0),z=(0,P.compactValues)({...(0,a.omitModeData)(C),...(0,P.pick)(B,"tz","tzSource","errors","inferred","duration"),dirFilters:F,dominantColors:O,fileFilters:I,needsTranscoding:await(0,m.needsTranscoding)(i),pathsInLibrary:N,pathToLibraryAsset:(0,g.pathToLibraryAsset)((0,S.localToDate)(C.capturedAtLocal),i),priorAssetFile:L?.toJSON(),priorIsInSync:R,sidecars:(await i.existingSidecars()).map((e=>e.base)),tagResult:A,validFile:(0,b.notBlankOr)(await(0,f.whyInvalidFile)(i.nativePath),"OK"),variantSortCriteria:(0,n.assetFileSortCriteriaPojo)(C),whyExcludedDirectoryRecursive:await(0,l.whyExcludedDirectoryRecursive)(h),whyRejected:j});return(0,P.compactValues)({nativePath:i.nativePath,mimetype:o,...(0,r.sortedKeys)(z)})}catch(t){return{nativePath:(0,h.toNativePath_)(e),error:(0,o.errorToS)(t)}}}},30690:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),D=i(87748),E=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),O=i(89452),A=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=O.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,E.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,A.toAssetId)(this)}renderCaption(e){return(0,E.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,E.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,s=W,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),D=i(65642),E=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),O=i(11944),A=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),H=i(61570),q=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),Z=i(13222),X=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Z.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,H.assignAllFields)(this,(0,H.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=x.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,A.at)((0,A.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,A.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,E.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,s=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),s=i(75556);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),s=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),s=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},77910:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(53525),s=i(88491),n=i(75556),a=i(1724);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),s=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),s=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),s=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),D=i(1429),E=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),O=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,O.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,E.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,E.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,D.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,E.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,E.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,E.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),s=[];for(const n of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),s.push(e)}}return s}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,E.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),s=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,s.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const s=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=s)return void c().debug("applyOnce(): already done",{priorCompleted:s});const n=this.ops().insertOne(e),o=await t(n);return(0,r.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function D(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=D;class E extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),E.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??D(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:s.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=E.minCreatedAt(),t=E.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=E,E.$tableName="Progress",E.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),s=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),s=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),D=i(39784),E=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),O=i(14405),A=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,D.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),A.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),A.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(O.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,E.fmt)(e.length)+" of ")+(0,E.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(O.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(O.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),s=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const s=c.$tableName;this.dbl.runScript([`INSERT INTO ${s}(${s}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),s=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),s=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),s=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,s.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},16630:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const o=i(4866),l=i(7162),u=i(67654),c=i(46852),d=i(7383),h=i(39506),f=i(53525),m=i(98250),p=i(72461),g=i(31216),y=i(47874),v=i(43414),w=i(96593),b=i(11944),S=i(59694),P=i(39938),M=i(88491),_=i(66776),T=i(75556),D=i(30690),E=i(89452);t.isFileInSync=async function(e){return new x(m.PosixFile.for(e)).alreadySynced()};const k=new h.SerialLaterQueue;class x{constructor(e,t){this.file=e,r.set(this,void 0),s.set(this,new Set),this.alreadySynced=(0,d.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>a(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,d.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new E.AssetFile).updateFromFile_(this.file);return null==e?a(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,o.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,o.lazy)((()=>v.Settings.useImageHashes.valueOrDefault?(0,p.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,o.lazy)((()=>(0,c.thenMap)(this.imageHash(),(e=>(0,b.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,o.lazy)((async()=>{const e=await this.capturedAt_();return a(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,d.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,P.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return a(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return a(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,d.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,g.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtOrImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,d.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return a(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;a(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw a(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),n(this,r,(0,l.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f"),this.ctx=(0,y.forceContextOrSetting)(t)}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),a(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}a(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(){const e=await this.file.uri_();if(null!=e)return E.AssetFile.ops().findOneBy({uri:e})??E.AssetFile.ops().findOneBy({uri:this.file.fileuri()});a(this,r,"f").warn("byUri() uri is null",{file:this.file})}assetByNormalizedPathUri(){return(0,c.thenMap)(this.file.normalizedPathUri_(),(e=>D.Asset.findFirstByFile((t=>t.where("AssetFile.uri",e)))))}assetBySha(){return(0,c.thenMap)(this.file.sha(),(e=>D.Asset.findFirstByFile((t=>t.where("AssetFile.sha",e)))))}async assetByCapturedAtOrImageHash(){const e=await this.capturedAt_();if(null==e)return a(this,r,"f").throw("Cannot import, capturedAt is null"+f.InternalErrorFlag);if(v.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(E.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=v.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=E.AssetFile.query();return(0,T.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(M.secondMs,v.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,d.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)a(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(v.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void a(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const n=await this.dominantLabhashes();if((0,b.isNotEmpty)(n)){const t=e.localBoundaries({delta:4*s});if(null==t)a(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",n).orWhereIn("mode1",n).orWhereIn("mode2",n))));if(null!=e)return e}}return this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash))}))}async firstSimilarAssetByQuery(e,t){a(this,s,"f").size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(a(this,s,"f"))));const i=await this.firstSimilarAsset(E.AssetFile.ops().all(t));return null!=i&&a(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const n=(0,S.sortBy)(e.filter((e=>!a(this,s,"f").has(e.id))),(e=>[(0,_.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of n)if(null!=e){await e.getNativePath();const i=E.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const n=(0,u.whyNotSameAsset)(t,e,i);if(null==n)return a(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);a(this,s,"f").add(e.id),a(this,r,"f").debug("Contemporary assetFile not similar: "+n,e?.uri)}}}t.AssetFileFinder=x,r=new WeakMap,s=new WeakMap},97840:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),D=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function b(){const e=[],i=[];for(const r of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(r)){const s=await(0,v.nativePathToUriPath)(r);null==s?(e.push(r),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",r)):i.push(s)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",r);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await b()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),b=i(36310),S=i(65548),P=i(71766),M=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await S.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),s=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=s.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=s.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,r.leastBy)(s,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),b.Operation.markOpCompleted({name:b.OperationNames.forceRestartSync}))}function D(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function E(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,s.lazy)((async()=>{const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),r=await(0,t.getStaleCompletedAt)(),s=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:s===e.nativePath,status:D(e,r),isNext:e.nativePath===i?.nativePath,lastStartedISO:E(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:E(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const r=i(3874);async function s(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=s,t.posixFileToUriPath=async function(e){return s(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return s(e,(0,r.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),s=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,s.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),D=i(8199),E=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),O=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return O().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const A=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:A,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=O().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(s.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),s.info("vacuuming orphan tags..."),await L()}catch(e){O().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(A,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),O().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,D.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,E.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")},71017:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=82118);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),s=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),s=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:s}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const r=i(6113),s=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:s}=i(35740);s||(s=e=>null!=e&&e instanceof r),e.exports=s},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:s}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),s=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),s=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:s}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),s=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),s=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),s=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),s=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:s}=i(42421),{post:n}=i(97362),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),s=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),s=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),s=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),s=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),s=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),s=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(s.isProd?"":`-${s.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),s=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return D(e,t,i).index}function D(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=D(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=E,t.collectBatched=function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const s=r(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class D extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:s.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=D,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class s{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=s},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let s=!(0,r.noColor)();function n(e,t){return i=>s?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){s=e??!(0,r.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),s=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),s=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),s=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),s=i(4866),n=i(98250);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),s=i(40786),n=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),s=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){s(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),s=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),s=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),s=i(74269),n=i(78109);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),s=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),s=i(51498);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),s=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const s=r(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&s.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=s.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},46954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(43383),s=i(49849);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),s=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,s]of(0,u.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,u.keys)(e))if(r[n]=t(n,e[n]),s++,(0,l.gt)(s,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),s=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const D={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},E={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,D)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,E);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),s=i(39784),n=i(21142);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const s=i(5712),n=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),D=i(4586),E=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),O=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),A=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))O().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,l.isEmpty)(s))return O().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){O().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){O().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){O().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(O().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,E.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,s.pidExists)(r)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),s=t.getTime(),n={...e,cmd:r,startTime:s};return await i.writeJson_(n),O().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void O().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{O().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,D.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function E(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=D,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],O))}());return(0,o.sortBy)(e.filter(D),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(E([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[s.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=E;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===s.default.pid))||r.push({pid:s.default.pid,start:new Date(v.StartTs),cmd:"node "+s.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),s=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),s=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...s)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=s,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return s.promise}(...s)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),s=i(82798);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),s=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,s.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const s=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return s.setShim=e=>{i=e},s.hasShim=()=>null!=i,s}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),s=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,s.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),s=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),s},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),s=this.valueOf(this.store[r]);if(e===s)return{found:!0,index:r};e>s?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),s=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),s=i(18991);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+s+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const D=/^['โ€˜โ€™].*['โ€˜โ€™]$/,E=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),D.test(e)||E.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function D(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=D,t.paddedPositionalDiff=function(e,t,i=8){return D((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),s=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),s=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},46080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(39784),s=i(13779),n=i(1440),a=i(43414),o=i(67654),l=i(92356);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},67654:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(24603),o=i(66776),l=i(75556),u=i(61570),c=i(17078),d=i(84593),h=i(85563),f=i(7162),m=i(34928),p=i(72461),g=i(32148),y=i(43414),v=i(65642),w=i(74873),b=i(27446),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} โ‰  ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} โ‰  ${r.aKey}:${r.aValue})`}function D(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const D=P(e,i,"make",_)??P(e,i,"model",_);if(null!=D)return D;const E=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(E,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(E)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:k});const x=(0,s.compact)((0,u.values)(k));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos โ‰  images",t.whyNotSameAsset=function(e,t,i){{const i=D(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=D(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==D(e,t)},t.whyNotSimilarAssetFile=D},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),s=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const D=["make","model","rating","cameraId","imageId","lensId","geohash"];function E(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of D)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=E,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of E(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(92332)),n=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),D=i(46234),E=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class O{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new s(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,D.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new E.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===D.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==D.PromiseStates.pending}get isResolved(){return p(this,o,"f")===D.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===D.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,D.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,D.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=O,s=O,m=function(e){if(p(this,o,"f")===D.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}},r=new WeakMap,s=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=r.isTest?e:e||s}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,s,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,s,"f")?void 0:Date.now()-d(this,s,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,s,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),s=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let s,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:s):(n=!0,s=(0,r.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>s,o.force=async()=>(await s,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),s=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(s)?(0,d.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=s?b.PermissivePromises:new b.Promises(i,(()=>s))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(s);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){s=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},39506:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),s=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,s.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),s=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,n.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function D(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(s.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=D,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let E=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...D(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(s);if((0,m.isLogged)("debug")&&!E){E=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(s),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return s}t.childEnv=k},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(17718)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),D=i(79141),E=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function O(e,i,r,s=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),s-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function A(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),O(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=A(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,E.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||s?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new D.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),O(s.default.spawn(e,t,n),e,t,i)},t.execFile=A,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95298:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),D=i(45512),E=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,E.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,D.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const s=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=s?a.join("$library",i.posixPathFrom(s)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),s=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,s.exit)(0)})),e.parse(s.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),s=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,s.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),s=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(43414),s=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(r.Settings.logColor.envValue=!1),(0,s.map)(e.color,(e=>r.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(43414),s=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),s=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),s=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>D(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function D(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=D;const E=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function I(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function O(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(E,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return O(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=O,i.c[i.s]===e&&console.log(D([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),s=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,D=(y+v)/2;let E;y*v==0?E=w+b:(E=(w+b)/2,E-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,E+=2*(E<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(E-Math.PI/6)+.24*Math.cos(2*E)+.32*Math.cos(3*E+Math.PI/30)-.2*Math.cos(4*E-63*Math.PI/180),C=1+.015*k/(0,s.sqrt)(20+k),F=1+.045*D,I=1+.015*D*x,O=30*Math.PI/180*Math.exp(-1*((180/Math.PI*E-275)/25)**2),A=2*(0,s.sqrt)(Math.pow(D,7)/(Math.pow(D,7)+Math.pow(25,7))),L=-1*Math.sin(2*O)*A;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),s=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of D({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),E(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),O=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(O),pixelCount:f.length}),{dominantColors:O,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function D({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),D({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function E(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=D,t.dominantColorsFromModes=E,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),s=i(61570),n=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),s=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),s=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function D(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function E(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=D(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=D,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):E(e)},t.datedToDateTime=E,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),s=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),s=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),s=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),s=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),s=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function D(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class E{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tD(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return s.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new E(t.year,t.month,t.day)}}function k(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(s=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=E,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${D(n)}:${D(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>D(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new E(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function O(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?s.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(O(e,t),l.dayMs)},t.diffMillis=O,t.closeTo=function(e,t,i){return(0,u.mapOr)(O(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(r+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=s.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},s=(0,M.normalizeZone)(t);if(null!=e&&null!=s&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(s,r):k(e)?.setZone(s,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,T.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),D=i(50140),E=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:A.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return A.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return A.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=O({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,E.isDateTime)(i)?i:(0,D.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function O({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of A.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=O;class A{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=O({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=A,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},A.instance=(0,u.lazy)((()=>new A));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),s=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),s=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),s=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),s=i(59694),n=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,D=/[-โˆ’]/,E=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=D.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,E,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,O=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function A(e){return F(O().exec(e))}t.ianaZoneToOffsetMinutes=A,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=A(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function D(e){if(null==e)return!1;const t=k(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return D(e)?e:void 0},t.isValidDate=D;const E=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===E)return E;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof s.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=s.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return D(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function O(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function A(e,t,i){return(0,u.gt0)(i)&&s.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||O(t,e))&&(!(0,u.gt0)(i)||A(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=O,t.validDay=A,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),s=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),s=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),s=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),s=i(7162),n=i(61253),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),s=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),s=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),s=i(19658),n=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(s.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),s=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,s.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let s;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();s=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:s});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),s=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),s=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),s=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),s=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},34879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(20681),s=i(69317),n=i(22143),a=i(53719),o=i(85890);t.sqliteVersion_=(0,r.lazyAsync)({later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),s=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),D=i(10156),E=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+E(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+E()),preexistingDir:i});return e}}function x(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+E(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),s=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(14889),o=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),s=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),s=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),s=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),s=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),s=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},96416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(4866),s=i(39938),n=i(87748),a=i(17078),o=i(7162),l=i(62936),u=i(10408),c=i(95725),d=i(76531),h=i(82041),f=i(82341),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),s=i(82798),n=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),s=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),s=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!s.isProd&&!(0,n.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),s=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(87561)),n=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(s.default.readFileSync(r)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(n))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),s=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),s=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),s=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),s=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),s=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,s.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),s=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),s=i(87489);function n(e,...t){return s.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,r.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),s.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),s=i(4866),n=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,s.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let s=!1;t.isSyncing=function(){return s},t.setIsSyncing=function(e){s!==e&&(s=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),s=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,s.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,s.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),D=i(43383),E=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),O=i(75556),A=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),se=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,O.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,O.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),s=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=s,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let s=!1;if((0,P.isEmpty)(i))return;const n=be((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),s||(s=p(this,r,"m",f).call(this,e));s&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,O.gt)((0,H.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,E.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,A.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},s=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?s.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(s.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,s),this.save(),s)}}t.SharedState=Se,s=Se,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),b.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:s}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(s)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,D.defer)((()=>{ce.Settings.libraryDir.watchLater(p(s,s,"f",u)),ce.Settings.cacheDir.watchLater(p(s,s,"f",u)),ce.Settings.sharedStateDir.watchLater(p(s,s,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,se.nativePathsEqlSync)(e,s.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(s.instance()),s.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(s,s,"f",l).call(s);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new s(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),s=i(79015);let n=!1;(0,r.later)((()=>(0,s.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(87561)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),s=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),D=i(88491),E=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),O=i(98510),A=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),se=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const s=(0,he.resolve)(i),n=new Se(s,t);return be().set(i,n),be().set(s,n),n}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,E.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,A.pad2)(t+1),(0,A.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,D.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,D.unixtime)(t)>=(0,D.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,D.unixtime)(t)>(0,D.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,O.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*D.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:D.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*D.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),s=i(17310),n=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),s=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),s=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),s=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,s.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const s=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(s);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(s,(async(e,i)=>{g().trace("callback",{nativePath:s,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:s}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(s,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,s.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),D=i(20902),E=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),O=i(98462),A=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:O.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?E.LogLevels.debug:E.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,D.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:se,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,S.thenNot)((0,A.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),b=i(77696),S=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,s.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,r,"m",a).call(this)}),o(this,s,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,s=new WeakMap,r=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,b.fmtFullDuration)(this.staleMs," ")});const i=await l(this,r,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,S.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,s,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),s=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,s.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),s=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,s.pick)(await(0,r.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),s=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(66776),s=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),_=i(92332),T=i(11944),D=i(37609),E=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),O=i(20636),A=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,s,Math.max(Date.now(),w(this,s,"f",n)+1),"f",n),(0,T.compactBlanks)([H.TokenRadix.encode(w(this,s,"f",n)),N.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return w(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=s,s,(i=w(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(s,s,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:E.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(s,s,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+E.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),s=i(44726),n=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),D=i(79015),E=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),O=i(95725),A=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,E.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,E.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,O.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,s,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,s,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,s,"f")});const e=c(this,s,"f"),i=await(0,A.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,s,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,D.ee)().emit("fileChanged",this.targetNativePath),u(this,s,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,O.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,s,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,s,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),s=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44470)),n=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(6005)),n=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),s=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),s=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),s=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),s=i(44726),n=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),s=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return D(e,i,t);const r=await Promise.race([T(e,t),E(e,t)]);return t.halt(),r}(t.nativePath)))}async function T(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function D(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function E(e,t){const i=await(0,m.readdir)(e);return null!=i&&D(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function E(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(g.isLinux?r===s:(0,m.equalsIgnoreCase)(r,s))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=E,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=x(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),F([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("โ€ฆ"),F([...s,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await s.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>E({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),D=i(61570),E=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),O=i(14889),A=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),se=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:O.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,A.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,A.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,A.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,A.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,D.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,A.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,A.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,E.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:O.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(O.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(O.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,A.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function D(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function E(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function O(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function A(e){return[...O(e),{notMissingMimeType:D},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:E},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??A(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=O,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...O(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...O(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...O(e))},t.expensiveFileFiltersFor=A,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>s.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(s.default.join((0,t.execDir)(),"resources"),s.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=s.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),s=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),s=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),s=i(51081);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(s===h.Timeout&&(0,p.onTimeout)({soft:!1}),s!==h.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):D(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=D},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const s=r(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return s.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),s=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),s=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const s=r(i(87561)),n=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(P(r),P(s));if(null==n||n>1)return"unmatched "+i+": "+r+" โ‰  "+s}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const s=r(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),s=i(6314);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),D=i(91641),E=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),O=i(18849),A=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const H=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function q(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return q().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,s,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=q,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return q().descendants((async e=>(0,A.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends E.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),D.EndableRanks.service),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,s,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,O.stack)()});{this.logger.log(H.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),s={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([s],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return l(this,n,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,s,"f")}}t.SyncReport=$,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,s,function(){const e=c.DateTime.now();return q().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,s,"f").nativePath),this.logger.info("Opening new report: "+l(this,s,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,s,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,s,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),s=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),s=i(14889),n=i(95725);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),s=i(34996);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},81286:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(10408),a=i(96593),o=i(83135),l=i(79403);t.exiftoolHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifToolโ€ฆ",settings:[],later:async()=>{try{const e=await(0,a.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,o.ver)(e),(0,r.tt)((0,a.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}catch(e){return{level:"error",msg:"Something's amiss with ExifTool: "+(0,n.errorToS)(e)}}}})))},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(93977),o=n(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},2882:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(43383),s=i(15203),n=i(13699),a=i(79403);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directoriesโ€ฆ",settings:[],later:n.externalDirectoryCheck})))},44606:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const s=r(i(52167)),n=i(43383),a=i(43947),o=i(77125),l=i(7162),u=i(55568),c=i(14889),d=i(20681),h=i(43414),f=i(19209),m=i(36297),p=i(79403),g=(0,n.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({later:async()=>{try{if(!(0,u.isWebService)()){const e=f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}).toString(),t=await s.default.get(e,{timeout:c.ShortCommandTimeoutMs}),{status:i,data:r}=t;if(m.HttpStatusIs.ok(i)&&(0,o.isHealthCheckSummary)(r))return r.libraryDir!==(h.Settings.libraryDir.valueOrDefault??null)?void g().error("getHealthSummary(): libraryDir mismatch",{local:h.Settings.libraryDir.valueOrDefault,remote:r.libraryDir}):(g().debug("getHealthSummary()",{url:e,status:i,data:r}),r);g().warn("getHealthSummary(): invalid response",{url:e,status:i,data:r})}}catch(e){g().warn("Failed to get health check summary from web service",{error:e})}},ttlMs:c.ShortCommandTimeoutMs}),t.getLocalHealthSummary=(0,d.lazyAsync)({later:()=>p.HealthCheck.awaitSettled(),ttlMs:c.ShortCommandTimeoutMs}),(0,a.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},79403:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),D=i(66776),E=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),O=i(13779),A=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),Z=i(18295),X=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,s,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,s,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,s,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,s,"f",l).toA()}static addLoadingMsg(e){v(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,s,"f",h).entriesByCountDesc()}),(0,D.map)((0,O.leastBy)(e,(e=>[v(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,D.map)(e,(e=>v(this,s,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return v(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=s.summary();if(t.settledCountv(s,s,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>s.onResultChange(),onError:()=>s.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,O.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,s=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,s,"f",n),(e=>!e.isPending)),v(this,s,"f",n)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Z.summarizeHealthChecksSync)({errors:v(this,s,"f",l),skipPending:v(this,s,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,s,!0,"f",u),t.state!==v(this,s,"f",c).last?.state&&v(this,s,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,E.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=s.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,D.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new A.BoundedList(10)},u={value:!1},c={value:new A.BoundedList(10)},d={value:new A.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(s,s,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(s,s,"m",m).call(s))),Q.resetDebounced=(0,N.debounce)((()=>s.reset()),50)},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),s=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},46747:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(4866),s=i(36535),n=i(43383),a=i(77125),o=i(7162),l=i(19658),u=i(29405),c=i(79015),d=i(82041),h=i(81286),f=i(2882),m=i(79403),p=i(61099),g=i(71664),y=i(28482),v=i(22627),w=i(32940),b=i(17938),S=i(40715),P=i(11560),M=i(44454),_=i(93763),T=i(97596),D=i(74113),E=i(23119),k=i(59415),x=i(20610),C=i(9335),F=i(12358),I=i(84729),O=i(42386),A=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test checkโ€ฆ",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,D.settingsEnvHealthCheck)(),(0,k.settingsSystemHealthCheck)(),(0,E.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,M.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,_.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,I.videoHealthCheck)(),(0,O.volumeHealthCheck)(),(0,F.versionHealthCheck)(),l.isProd||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(A().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{A().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},61099:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(71923),u=i(15203),c=i(83135),d=i(79403);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC toolingโ€ฆ",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},71664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(66776),a=i(10408),o=i(22143),l=i(15299),u=i(49849),c=i(83135),d=i(79403);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"โ€ฆ",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK","jpegtran is a supported version.",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),s=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},28482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(24586),l=i(82341),u=i(10408),c=i(3955),d=i(15203),h=i(51053),f=i(43414),m=i(82041),p=i(32421),g=i(79403),y=i(91499);async function v(){const e=await(0,l.setupLibraryDirs_)();return(0,m.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}async function w(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(f.Settings.libraryDir.toEnvLine(f.Settings.libraryDir.defaultValue))}`]};const t=await(0,p.mountpoints_)(),i=(0,c.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[y.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`];return null!=t&&(0,a.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}return await v()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}.`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}}async function b(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:"No PhotoStructure library is open"};if(!(0,m.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",f.Settings.libraryDir.hasValue()?(0,r.tt)(f.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await v():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}t.libraryDirectoriesCheck=(0,n.defer)((()=>g.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directoriesโ€ฆ",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,d.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:(0,d.isDocker)()?w:b})))},22627:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(75556),l=i(61570),u=i(17078),c=i(82341),d=i(42648),h=i(43414),f=i(46573),m=i(79403);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)โ€ฆ",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},17938:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(97742)),n=i(36535),a=i(43383),o=i(46954),l=i(83135),u=i(79403);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.jsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},40715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(43383),s=i(27175),n=i(51053),a=i(79403);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directoryโ€ฆ",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},11560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(43383),s=i(55463),n=i(79403);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating systemโ€ฆ",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},44454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(10408),a=i(51053),o=i(71663),l=i(83135),u=i(79403);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShellโ€ฆ",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},93763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(34879),a=i(10408),o=i(83135),l=i(79403);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLiteโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},97596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(75556),o=i(24586),l=i(42648),u=i(29405),c=i(60052),d=i(51053),h=i(79403);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission levelโ€ฆ",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},74113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(17078),a=i(43414),o=i(77016),l=i(79403);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},23119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(43383),s=i(82041),n=i(79403),a=i(59415);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settingsโ€ฆ",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},59415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(17078),o=i(91464),l=i(10408),u=i(98250),c=i(82041),d=i(98024),h=i(79403);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},20610:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=t.sharpHealthCheck=void 0;const s=r(i(39084)),n=i(71017),a=r(i(57441)),o=i(43383),l=i(24603),u=i(87748),c=i(61570),d=i(10408),h=i(27175),f=i(79403);async function m(e){const t=e??(0,n.join)(h.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(t,{failOn:"error"}),r=await i.resize(31,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,l.eql)((0,c.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:31,height:32,channels:3}),"Unexpected sharp output: "+(0,u.stringify)(r.info))}t.sharpHealthCheck=(0,o.defer)((()=>f.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharpโ€ฆ",settings:[],later:async()=>{try{return await m(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,d.errorToS)(e)]}}}}))),t.testSharp_=m},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),s=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},9335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(43414),l=i(11053),u=i(79403);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system loadโ€ฆ",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},12358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(57310),a=i(79403);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure versionโ€ฆ",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},84729:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(46517),u=i(15203),c=i(83135),d=i(79403);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video toolingโ€ฆ",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},42386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(20636),l=i(17078),u=i(13779),c=i(14889),d=i(51053),h=i(7903),f=i(69551),m=i(53719),p=i(46573),g=i(79403);t.volumeHealthCheck=(0,a.defer)((()=>g.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumesโ€ฆ",settings:[],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:d.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,p.volumes)(),(0,m.commandTimeoutMs)());if(i===o.Timeout){const i=await(0,o.thenOrTimeout)(d.isWin?(0,f.getLocalVolumesWin_)():(0,h.dfPosixRawLocal_)(),c.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===o.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following mountpoints:",(0,s.li)(a.map((e=>e.mountpoint)))]};const[g,y]=(0,u.partition)(i,(e=>!0===e.remote));return{level:"ok",msg:["Volumes seem OK",(0,l.plur)(y.length,"local volume")+" and "+(0,l.plur)(g.length,"remote volume")+" checked."]}}})))},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),D=i(43414),E=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),O=i(14489),A=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,s.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const s=i.sha??await r.sha();if(null!=s)if(!0!==await(0,t.isBadSha)(s))try{return await this._build(r,i)}catch(t){e.push(t),L().set(s,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,A.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:a,height:o,sha:l,mimetype:u}=t;if(null==s||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(r,s);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&D.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=D.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),s=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),s=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),s=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),s=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),s=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),D=i(68107),E=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function O(e){const t=w.PosixFile.for(e),i=await(0,D.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?E.dctHash:E.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function A(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:O}),t._imageHash_=O,t.isImageHash=A,t.toImageHash=function(e){if(null!=e){if(A(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(A(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),b=i(60346),S=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),D=i(72461),E=i(36143),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,D.isImageHash)(e.a)&&(0,D.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=D.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function I({a:e,b:t,greyscale:i,dim:r=D.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function O(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,D.imageHash)(e),await(0,D.imageHash)(t),r)})}function A(e,t,i={}){const r=(0,D.toImageHash)(e),s=(0,D.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=I({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=I({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),O=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),A=[];P&&A.push(`aspect ratio mismatch (${(0,E.fmtAspectRatio)(v)} vs ${(0,E.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&A.push("different image content ("+(0,l.andList)(L)+")");const j=g>=O,z=j&&N.avg>=F;j||A.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:O,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(A)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return A(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=D.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=I,t.isSimilarImage=O,t.compareImageHashes=A,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return O(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(A(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(A(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),s=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),s=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),s=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(889),n=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),D=i(84685),E=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),O=i(49312),A=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const n=await(0,E.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),A=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,D.orientationRequiresMirroring)(a.orientation);if(!0===i||g||A||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:A,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=s.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*s.secondMs},p1:{x:20*o.MB,y:12*s.secondMs}},p={p0:{x:11*o.MB,y:12*s.secondMs},p1:{x:26*o.MB,y:24*s.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,s=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+s+n+c+d),dbMs:i,tagMs:s,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),s=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),s=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),D=i(49586),E=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),O=i(68107),A=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),s=E.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??E.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:E.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:E.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,O.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,L.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,E.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,A.commandTimeoutMs)()}),s.nativePath}async function q(){return E.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,E.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(E.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const r=j("transcode",e),s=$.get(t.nativePath);if(null!=s&&!(0,n.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:s.name}),s.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),s=(0,x.extractDurationSec)(r),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,s={src:e,...V(e,d)},n=J(o,s.videoBitrateKbps,i),a=E.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(s.width=(0,u.roundEven)(e.width),s.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));s.dest=i,s.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(s));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function D(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=D;const E=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await D();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await D(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await D(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...O(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await D(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),s=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,s.lazy)((()=>(0,r.toGt0)(n.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),s=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const D=["-T"],E=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...D,...E,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),O=[];function A(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});O.push(r)}}I.on("error",A),I.stderr.on("data",A);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,s.isNotEmpty)(O))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:O,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),s=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),s=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),D=i(43414),E=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,E.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function A(e,i,r,s){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await O(e),sids:null!=s?s:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=A,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await A(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),r=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(D.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,s.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),s=i(4866),n=i(39938),a=i(10508);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),D=i(10508),E=i(73435);t.k=(0,a.defer)((()=>(0,D.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,E.toUID)(E.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function O(){return P.isLinux?(await I("lm")).map((e=>(0,E.toUID)(E.S.lm,e))):void 0}async function A(){return P.isLinux?(await I("lp")).map((e=>(0,E.toUID)(E.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,E.toUID)(E.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,E.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,E.toUID)(E.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,E.toUID)(E.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,E.toUID)(E.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,E.toUID)(E.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,E.toUID)(E.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,E.toUID)(E.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,E.toUID)(E.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,O,A,L,B,U,H],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return k().tap({msg:"sids()",result:(0,E.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)q.add(t)},t.clearSids=function(){f.isTest&&q.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),s=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),s=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),s=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),s=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),s=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(4866),s=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),s=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),s=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>s(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),s=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,s.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),s=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),s=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),D=i(3955),E=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),O=i(98968),A=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,E.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,D.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,O.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,O.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,D.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,O.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,O.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,A.readLogEntries)(e,{start:r,end:i}),(e=>(0,O.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),s=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),D=i(83837),E=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),O=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class A extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,s,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,O.recentLogEntries)()),(0,O.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=A,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,D.endStream)(e.stream),E.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),s=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),s=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),s=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,s.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const s=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&s.push(y.ConsoleLogger.instance()),(0,n.map)((0,b.logBroadcaster)(),(e=>s.push(e))),l.rootLoggers.set(s),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),D(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,s.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const D=(0,s.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},60346:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,s=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),s=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),s=i(89965);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),s=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),s=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),s=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),s=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),s=i(3331);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),s=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),s=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),s=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),s=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),s=i(4866),n=i(82798);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),s=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),s=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),s=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),s=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),s=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),s=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),D="{ready}",E=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${D}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:D,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,E),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,E),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),s=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),s=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),s=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,s.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,s.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),s=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){D(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&E()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(g.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function D(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function E(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=D,t.disableExternalNetworkRequests=E},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),s=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),s=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),s=i(63774);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),s=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,s.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,s.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,s.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,s.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),s=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),D=i(7560),E=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),O=i(51053),A=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),se=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>O.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!O.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>O.isMac?"100ms":O.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:O.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,A.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>O.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,E.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,A.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(O.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:se.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(s.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(s.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),s=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>s.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:s.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),D=i(98462),E=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),O=i(95699),A=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(A.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(D.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function H(e){return(0,m.map)(z(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",q),(0,T.ee)().on("settingsChanged",q),I.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await D.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(s),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"old"}),await s.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Z(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(E.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(E.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),s=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),s=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),s=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),s=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),s=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),s=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},77016:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(61570),s=i(91464),n=i(29405),a=i(60052),o=i(43414);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a)null==a.value.opts.fromEnv(r)&&i.push({envKey:n,msg:`The value "${e[n]}" isn't valid for this ${a.value.constructor.name}.`});else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),s=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),s=i(91464);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),D=i(54809),E=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),O=i(43414),A=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,E.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],s=r;if((0,E.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(s))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,E.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",U(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??s("tags",U(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:s("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",q(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),s=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(889),n=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),D=i(21084),E=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),O=i(2023),A=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),Z=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),se=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,A.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new D.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new D.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=E.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,X.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,O.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,O.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,Z.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,Z.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=E.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,O.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=E.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function D(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return D({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=D,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),s=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),s=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),s=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),D=i(96593);function E(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=E,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function O(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,D._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,D.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const s=E(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),O(i,s,n)},t.ensureHistoryRecords=O},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,l.toDated)(t[r]);if(null==s||(0,h.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),s=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),s=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},65308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(66776),l=i(11254),u=i(39784),c=i(7162),d=i(1058),h=i(91464),f=i(6667),m=i(43414),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Zโ€˜โ€™']+[-A-Zโ€˜โ€™']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function M(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(M(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,D=b.length;if(_.length>0)if(0===T&&D>0)l.push(..._);else if(0===D&&T>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function M(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),r=M(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),s=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),s=i(75556),n=i(43414);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),s=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(r.length)),l=n(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),s=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),D=i(75123),E=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),O=i(96593),A=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,D.isSlowDir)(e.nativePath)&&!await(0,D.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,O.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(A.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),s=(0,E.findFileIndex)(e,r);if(s<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,O.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),s=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),s=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(s,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return D(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?D(this,!0):(null==this._formatted&&(this._formatted=D(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function D(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function E(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+E(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>E(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),s=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),s=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),s=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),s=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},33611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(4586),s=i(98250);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),s=i(39036);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),s=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},73037:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(82798),s=i(13779),n=i(49849),a=i(39036);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},17953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(61570),s=i(44726),n=i(39036);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},83135:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(39938);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},57310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.systemUserAgent=t.userAgent=t.checkVersion_=t.currentChannel=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(19067),l=i(9678),u=i(54883),c=i(7162),d=i(55463),h=i(14889),f=i(42041),m=i(20681),p=i(4586),g=i(76531),y=i(69060),v=i(43414),w=i(53719),b=i(15425),S=i(33611),P=i(38846),M=i(73037),_=i(17953),T=i(39036),D=i(83135),E=(0,a.defer)((()=>(0,c.mkLogger)("VersionCheck")));async function k(){return v.Settings.allowUserAgent.valueOrDefault?x():l.SimpleAppName}async function x(){return l.SimpleAppName+"/"+f.version+" ("+(0,d.osFullName)()+") "+(0,u.EditionType)().toLowerCase()+"/"+await(0,y.t)()}t.currentChannel=function(){const e=[v.Settings.updateChannel.valueOrDefault,(0,P.channel)()].map((e=>T.UpdateChannels.ordinal(e))).sort()[0];return T.UpdateChannels.values[e]??v.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(!v.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===v.Settings.optOut.value?e.push("Set "+(0,s.tt)(v.Settings.optOut.toEnvLine(!1))+" to enable."):!1===v.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,p.configDir)();if(null==i||!await(0,g.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const l=e?.installedVersion??f.version,c=(0,T.extractUpdateChannel)(l),d=(0,T.eligibleForChannel)(c),h=a.versions.filter((e=>d.includes(e.channel))).map((e=>e.version)),m=e?.latestVersion??(0,M.semverLatest)(...h);if(null==m)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+v.Settings.updateChannel.toEnvLine()]};const y=(0,T.extractUpdateChannel)(m),w="You are running "+(0,u.EditionName)()+" "+(0,D.ver)(l),b="The latest published "+(0,s.tt)(y)+" build is "+(0,D.ver)(m),S=y===c?void 0:"You should consider switching to the "+(0,s.tt)(y)+" channel.",P=Date.now()-a.updatedAt,_="Last checked "+(P{const e=(0,S.channelVersionsCache)(),i=await(0,b.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",config:{headers:{"User-Agent":await k()},timeout:h.ShortCommandTimeoutMs},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:f.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,_.isUpdateChannelVersion)(e)))||r.updatedByVersion!==f.version){if(i.fromCache)return E().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();E().throw("getChannelVersions_(): Invalid response",{result:r})}return E().tap({msg:"getChannelVersions_()",result:r})}})},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),s=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),s=i(55412),n=i(46573);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),s=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await O()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function D(e){return(0,l.map)(T(e),(e=>e+":\\"))}function E(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=D,t.getPsDriveCommand=E,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=D(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function O(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(D)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(E(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(I)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=O},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),D=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,D.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const E=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?E().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):E().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(E().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,D.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void E().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,D.mountpointsTtlMs)(),(()=>E().warn("gioVolumes(): timed out after "+D.mountpointsTtlMs+"ms")),(e=>E().log((0,s.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,D.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void E().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),s=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),s=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),D=i(43414),E=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),O=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function A(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){A(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{D.Settings.libraryDir.watchLater(A),D.Settings.scanPaths.watchLater(A),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=D.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||D.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),A()})),D.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=M,t=_,i=T){if(g.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),s=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),s=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function E(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>E(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=D,t.readVolumeUUID=E},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),D=i(91464),E=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),O=i(20902),A=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),se=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=s.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){se().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,D.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:ne}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){se().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));se().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return se().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const s=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return se().debug("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return se().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function ge(e,t,i){const r=i.filter((e=>(0,D.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,D.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,U.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,D.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return se().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return se().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,A.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return se().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(se().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void se().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,A.onError)("Timed out getting local volume metadata")));if(null==e)return void se().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;se().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){se().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,A.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return se().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,D.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(se().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},15425:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const s=r(i(52167)),n=i(43383),a=i(75556),o=i(7162),l=i(14889),u=i(36297),c=(0,n.defer)((()=>(0,o.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,a.gt0)(await t.size())&&(0,a.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await s.default.get(e.url,{timeout:l.ShortCommandTimeoutMs,...e.config}),n=r.data;u.HttpStatusIs.success(r.status)||c().throw("Failed",{url:e.url,response:r});const o=e.preCacheTransform?.(n)??n;return c().info("Fetch success. Caching",{args:e,json:o,cache:t}),await t.writeJson_(o),{data:o,updatedAt:Date.now(),fromCache:!1}}},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),s=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),s=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),s=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),b=i(91641),S=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),D=i(59387),E=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{E().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(1.2*_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:b.EndableRanks.first}),r.add(this),s.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??F()}}t.CpuUsage=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,F());const e=new C;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?Math.round(t/r*100):void E().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+S.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let s=!1;function n(){s&&(s=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return s},t.pause=function(e=!0){!1===e?n():s||(s=!0,(0,r.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),s=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),s.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),s=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),s=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),s=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),s=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),s=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),s=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),s=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),s=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),s=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),s=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),s=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,s.isFunction)(e)&&(0,s.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),s=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),s=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),s=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),s=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=s.length;(0,r.filterInPlace)(s,(t=>e(i,t))),t=t||n!==s.length,0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),s=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,s){return!(null==s||!l(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,s.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function D(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=D,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return D(0,100,b(t)?_(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),s=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),s=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),s=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),s=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),s=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),s=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),s=i(61570),n=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{r&&(0,s.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,s=!0){const n=await o(e,i,s);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const s=i-Date.now();return s<=0?t.Timeout:o(e,s,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return l(e,s,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:s=!0}){const a=await o(e,i,s);return a===t.Timeout?(0,n.tot)(r):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),s=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),s=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),s=i(82798);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),s=i(75556);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),s=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),s=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),s=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),s=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const r=i(4866),s=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),b=i(43414),S=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),D=i(94332),E=i(63216),k=(0,r.lazy)((()=>(0,s.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,E.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,r.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:b.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,r.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:b.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,r.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(b.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,r.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),O=(0,r.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),A=(0,r.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(b.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,r.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,D.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,D.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:b.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,S.compact)([x(),C(),F(),I(),O(),(0,w.LogDirCleanup)(),A(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},49374:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),D=i(46573),E=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),O=i(61570),A=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,D.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,O.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>A.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,E.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,E.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,n=new WeakMap,s={value:void 0}},93445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(23872),s=i(31216),n=i(9069),a=i(13222);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},13902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(4866),s=i(7162),n=i(80294),a=i(82341),o=i(43414),l=i(82041),u=i(53719),c=i(46573),d=i(88491),h=i(75556),f=i(17078),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.available{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),s=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,s.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),s=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(s.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+s),s):s}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i(0,l.mkLogger)("library.SuggestedLibraryDir")));class I{static async for(e,t){if((0,k.blank)(e))return;const i=await(0,T.bestVolumeForPath)(e,t);if(null==i)return void F().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,m.isLibraryDir)(e);return new I(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=_.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=_.Settings.minDiskFreeGb.valueOrDefault*C.GB){if(this.isLibrary)return;const t=await(0,P.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,b.containsHiddenPathname)(this.nativePath))return F().tap({...i,result:"contains hidden path"});{const e=await(0,w.whyExcludedDirectoryRecursive)(v.BaseFile.for(this.nativePath));if(null!=e)return F().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,y.canRWXFirstExistingAncestor)(this.nativePath)?(0,x.gt0)(e)&&this.availableBytesnew I(e,!1,{mountpoint:"/test",available:C.GB})))});const l=[],d=[],y=await i??await(0,T.volumes)();if(null==y||(0,D.isEmpty)(y))return F().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await I.for(t,y);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(F().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(_.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,p.picturesDir)());const w=[n.default.cwd(),...await(0,S.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,S.childDirectories_)((0,f.homeDir)())),(0,D.filterInPlace)(w,(e=>(0,b.isNotHiddenPosixPath)(e)));for(const e of w)await(0,m.isLibraryDir)(e)&&(F().info("current working dir is a library",e),await v(e));function P(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(F().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,f.homeDir)(),(0,a.AppName)())),await(0,h.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:y,f:e=>async function(e){try{if(await(0,m.isLibraryDir)(e.mountpoint))return F().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,S.childDirectories_)(e.mountpoint)){if(P())break;if(await(0,m.isLibraryDir)(t))F().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,S.childDirectories_)(t)){if(P())break;await(0,m.isLibraryDir)(i)&&(F().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());F().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){F().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),F().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const k=l;for(const e of(0,E.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(k.length>=t)break;k.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(F().debug("adding new path",e),k.push(e))}return(0,D.uniqBy)((0,E.sortBy)(k,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=I,t.suggestedLibraryDirs=(0,o.lazy)((()=>O())),t._suggestedLibraryDirs=O},98505:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(45161),s=i(35796),n=i(54883),a=i(79403),o=i(69060),l=i(95976),u=i(55463),c=i(33407),d=i(55568),h=i(43414),f=i(82041),m=i(45113),p=i(24586),g=i(42041),y=i(11053),v=i(59387),w=i(11944),b=i(39938),S=i(38625),P=i(19067),M=i(66776),_=i(75556),T=i(26588),D=i(44726),E=i(17078),k=i(30690),x=i(89452),C=i(50725);async function F(){if(null==k.Asset.db())return;const e=[];e.push((0,E.plurMetric)(k.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,D.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,E.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,E.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const I={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:I[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,M.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,M.map)(y.CpuUsage.instance().busyPct(),(e=>(0,_.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,_.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),s=i(85297),n=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},24709:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(91464),o=i(93125),l=i(43414),u=i(96593),c=i(28033),d=i(61473),h=i(11944),f=i(39938),m=i(61570),p=i(11254),g=i(82798),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},69258:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(43414),o=i(61473),l=i(11944),u=i(26588),c=i(30690),d=i(24709),h=i(51832),f=i(18290),m=i(96672),p=i(82355),g=i(7587),y=i(52465),v=i(40399),w=i(83089),b=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function S({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];t.some((t=>t.nativePath===e.nativePath))||t.unshift(e),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{b().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,g.lensTagFile)(e),(t=>{b().debug("Lens tag for "+e+":",t),u.push(t)})),await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{b().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,w.whoTagFiles)(t)??[];b().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,p.keywordTagFiles)(t,c),(t=>{b().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{b().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{b().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{b().debug("Album tags for "+e+":",t),u.push(...t)}));const S=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(y.normalizeTagRoot),o.joinTagPath)),P=await(0,y.tagDeltas)(i,S);return b().info("tagAsset("+e+")",{priorTagPaths:i,after:S,result:P}),P}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();b().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void b().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(b().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await S({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});b().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return b().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),b().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});b().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=S},51832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(96593),s=i(11254),n=i(11944),a=i(39938);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),s=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},96672:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(4866),s=i(7162),n=i(61473),a=i(22356),o=i(11944),l=i(49049),u=i(11254),c=i(89452),d=i(9069),h=i(63216),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},82355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(1058),o=i(91464),l=i(2073),u=i(46852),c=i(43414),d=i(96593),h=i(28033),f=i(61473),m=i(11944),p=i(59694),g=i(39938),y=i(43947),v=i(1429),w=i(66776),b=i(11254),S=i(82798),P=i(52465),M=i(83089),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function D(e){return _().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function E(e){return[...D(e.parent().posixPath),...D(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=D,t.extractPathnameTags=E;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(k,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,s]=(0,r.partition)(x(e),M.isWhoTag),n=(0,v.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(E)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},7587:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(46852),s=i(43414),n=i(96593),a=i(11254),o=i(11944),l=i(39938),u=i(66776);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),s=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},40399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(46852),o=i(15465),l=i(11944),u=i(39938),c=i(66776),d=i(90957),h=i(11254),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():(0,c.orElse)(m.get(e.trim().toLowerCase()),(()=>(0,n.capitalize)(e)))}t.friendlySubtype=y,t.fixCase=v},83089:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(4866),s=i(7162),n=i(43414),a=i(96593),o=i(71932),l=i(65308),u=i(61473),c=i(11944),d=i(39938),h=i(1429),f=i(61570),m=i(11254),p=i(39784),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},18130:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),D=i(88491),E=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class O extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=D.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*D.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),s=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:s,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,E.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,y.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=O,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,E.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),D=i(94332),E=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,E.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,E.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,D.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),s=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function D(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function E(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=D,t.fsLockForDb=E,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=D(e);return{...t,fslock:E(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),s=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,s.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},13915:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeSchemaJsonFile_=t.assertValidDbSchema_=t.schemaJsonFile=void 0;const s=r(i(49411)),n=i(13779),a=i(4866),o=i(7162),l=i(98250),u=i(27175),c=i(11944),d=i(51367),h=i(17078),f=i(91796),m=i(51603),p=(0,a.lazy)((()=>(0,o.mkLogger)("db.DbSchemaValid")));function g(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=g,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,m.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await g(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&p().throw("Db is missing "+(0,h.plur)(t.length,"table")+" : "+(0,d.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)p().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&(p().error("Missing columns",{expected:t,actual:e}),p().throw("Db is missing "+(0,h.plur)(i.length,"column")+" from table "+e.tableName+" : "+(0,d.andList)(i.map((e=>e.name)))))}}p().info("Validated schema.")}catch(e){throw(0,f.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return g(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,m.localTableInfo)(t)},{spaces:2})}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),s=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),D=i(43947),E=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),O=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,E.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(I.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,D.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,O.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),D=i(85476),E=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())E().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:D.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,D.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();E().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,D.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));E().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),s=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),D=i(6314),E=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),O=i(9069),A=i(70582),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,A.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,E.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,O.modelDb)()?.end()),await(0,A.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,E.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},s),o=new D.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),s=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),s=i(89253);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),s=i(43414),n=i(82798);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},91796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(42648),s=i(10408),n=i(79403),a=i(82041),o=i(36535),l=i(88491),u=i(43383),c=i(49374),d=i(13915),h=i(91894),f=i(77910),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library databaseโ€ฆ",settings:["libraryDir","forceLocalDbReplica"],ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{if(!(0,a.libraryHasSettings)())return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let e,t,i=!1;try{const s=Date.now();if(i=!1,t=c.Library.instanceRequired(),(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(await t.ready,e=await t.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(e),i=!0,await e.verify_(),await e.vacuum(),f.Heartbeat.assertPing_();const n=await t.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(e.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==e?void 0:"Live db is "+(0,o.tt)(e.dbFile.nativePath),null==t?void 0:"Local replica mode is "+(0,o.tt)(await t.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},39946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(4866),s=i(46747),n=i(82041),a=i(91796),o=i(23134),l=i(53829);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},23134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(13779),s=i(7162),n=i(98250),a=i(23872),o=i(79403),l=i(82041),u=i(11944),c=i(36535),d=i(43383),h=i(71766),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directoriesโ€ฆ",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},53829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(7162),s=i(46852),n=i(79403),a=i(43414),o=i(82041),l=i(47044),u=i(53719),c=i(27127),d=i(46573),h=i(11944),f=i(36535),m=i(43383),p=i(51367),g=i(89253),y=i(61570),v=i(71766),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumesโ€ฆ",settings:["scanAllDrives"],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" โ†’ "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},82118:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const r=i(10408),s=i(48843);process.on("unhandledRejection",(e=>console.error("UNHANDLED REJECTION",(0,r.errorToS)(e)))),process.on("uncaughtException",(e=>console.error("UNCAUGHT EXCEPTION",(0,r.errorToS)(e)))),(0,s.run)()},41634:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InfoArgs=void 0,t.InfoArgs={beforeParse:e=>e.option("--volumes","Emit a table with currently mounted volume metadata. See https://photostructure.com/volumes for details.").option("--mountpoints","Emit a table with currently mountpoints. See https://photostructure.com/volumes for details.").option("--sync-paths","Emit a table listing the paths that will be synced next.").option("--plan, --licensing","Emit plan/licensing information. See the About page in the web UI for more details or to activate a subscription.").option("--child-env","Emit the environment variables provided to all spawned processes.").option("--validate","Only run file validation on the given filenames (requires current PLUS subscription).").option("-j, --json","Emit metadata as un-indented, uncolorized JSON.").option("--load-library","Load the library database so more metadata can be shown (like if a file is currently in your library). This adds a second or two (depending on the size of your library).").option("--filter ",'Case-insensitively filter keys by . may have dots. Note that .nativePath is always included. Repeat to filter for multiple terms ("--filter foo --filter bar").',((e,t)=>t.concat([e])),[]).option("--file-filters","Include an exhaustive list of file and directory filters. This is hundreds of lines long, so it's not included by default.").option("--image-hash",'Automatically filter image hash fields. Equivalent to "--filter imageHash --filter imageHashComparison"').option("--flat","Only return values for objects with only one field").option("--suggested-libraries","Emit the suggested library directories (as seen on the settings page).").option("--volumes-ttl","Emit the volume cache time-to-live (use with --debug to see details).").option("--is-library ","Run a couple quick checks to see if looks like a PhotoStructure library.").option("--read-settings ","Read the given file and output the parsed settings.").option("--recount-all-tags","Recount every asset tag count. This may take a minute or two. Don't have a sync running concurrently. Implies --cleanup.").option("--globs, --exclude-globs","Emit all file and directory exclusion globs.").option("--health","Emit details for all health checks.").option("--doctor","Emit details for all health checks that aren't OK.").option("--skip-health","Disable health checks.").option("--version-check","Check now if the current version is the latest.").option("--table","Emit with console.table() (useful with --volumes or --filter).").option("--cleanup","Run a bunch of maintenance tasks."),afterParse:function(){}}},48843:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.run=void 0;const s=r(i(47261)),n=i(4866),a=i(7162),o=i(2023),l=i(55568),u=i(25516),c=i(63774),d=i(24586),h=i(46080),f=i(67654),m=i(75288),p=i(92356),g=i(2126),y=i(46852),v=i(21142),w=i(10347),b=i(37980),S=i(64063),P=i(9972),M=i(37445),_=i(77696),T=i(62936),D=i(1629),E=i(96416),k=i(82341),x=i(35796),C=i(10408),F=i(17875),I=i(79141),O=i(98462),A=i(64067),L=i(98250),R=i(22143),N=i(44606),B=i(79403),j=i(32148),z=i(31216),V=i(12737),W=i(69060),U=i(4657),H=i(43414),q=i(82041),G=i(98024),$=i(77016),J=i(47044),K=i(33611),Y=i(57310),Z=i(32421),X=i(53719),Q=i(46573),ee=i(11053),te=i(11944),ie=i(39938),re=i(38625),se=i(88491),ne=i(66776),ae=i(61570),oe=i(8199),le=i(7127),ue=i(17078),ce=i(39784),de=i(17146),he=i(49374),fe=i(13902),me=i(4958),pe=i(98505),ge=i(92045),ye=i(39946),ve=i(85223),we=i(41634),be=i(70750);t.run=async function(){try{await async function(){const e=await new b.CLI(le.ServiceNames.info,"[FILE...]",["* Omit any filenames to run diagnostics and output system configuration, tooling, and health check information.","* File paths should be absolute or relative to cwd.","* Provide 2 file paths to see why PhotoStructure may consider them variants of the same asset.","* To emit valid JSON, set NO_COLOR=1 or use --json."].join("\n")).add(we.InfoArgs,M.WriteSettingsArg,ge.LogArgs,S.ColorArgs,P.TimingArg).parse(),t=e.opts(),i=(0,te.uniq)(e.args),r=(0,re.isTrue)(t.flat),g=(0,re.isTrue)(t.table),F=(0,re.isTrue)(t.recountAllTags);F&&(H.Settings.recountAllTags.envValue=!0);const I=F||(0,re.isTrue)(t.cleanup);(0,re.isTrue)(t.imageHash)&&(t.filter??(t.filter=[]),t.filter.push("imageHash"),t.filter.push("imageHashComparison"));const Se=(0,re.isTrue)(t.fileFilters),Pe=(0,n.lazy)((()=>{if((0,te.isEmpty)(t.filter))return;const e=(0,ce.toA)(t.filter);return r&&i.length<=1||e.unshift("nativePath"),2===i.length&&e.push(...e.map((e=>"a."+e)),...e.map((e=>"b."+e))),e}));function Me(e){e=function(e){const t=Pe();return null==t?e:Array.isArray(e)?e.map((e=>(0,ae.pickDeep)(e,...t))):(0,ae.pickDeep)(e,...t)}(e),r&&(e=(0,ae.flattenObject)(e));const i=(0,re.isTrue)(t.json);r&&(0,oe.isPrimitive)(e)?console.log(e):i||(0,re.isFalse)(H.Settings.logColor.value)?console.log(JSON.stringify(e,void 0,i?void 0:2)):g?console.table(e):console.log(s.default.inspect(e,{depth:7,colors:!0,maxArrayLength:1024}))}if((0,u.setServiceName)("info"),(0,re.isTrue)(t.skipHealth)&&B.HealthCheck.disableAll(!0),(0,ie.notBlank)(t.readSettings)){const e=await(0,q.importFileSettings_)(O.BaseFile.for(t.readSettings));return Me({settings:(0,ae.fromEntries)(e.settings.map((e=>[e.name,e.value]))),warnings:e.warnings})}if(await(0,q.readSettings)(),I&&(l.isDbJanitorService.set(!0),H.Settings.logLevel.isUnset()&&(H.Settings.logStdout.envValue=!0,H.Settings.logLevel.envValue="warn",(0,U.setupLogger)())),(0,re.isTrue)(t.versionCheck))return await((0,K.channelVersionsCache)()?.unlink()),H.Settings.autoUpdateCheck.tmpValueIfUnset=!0,Me(await(0,Y.checkVersion_)());if((0,re.isTrue)(t.globs)||(0,re.isTrue)(t.excludeGlobs)){const e=(0,A.excludeGlobs)();return Me({excludeGlobs:{file:e.file.map((e=>(0,ae.pick)(e,"pattern","desc"))),dir:e.dir.map((e=>(0,ae.pick)(e,"pattern","desc")))}})}if((0,re.isTrue)(t.volumes)){const e=await(0,Q.volumes)();if(null!=e)return Me(e.filter((e=>!0!==e.ignorable)).map((e=>({filesystem:e.filesystem,...e,size:(0,ue.fmtBytes)(e.size),used:(0,ue.fmtBytes)(e.used),available:(0,ue.fmtBytes)(e.available),volsha:(0,J.volsha)(e.uuid)}))));console.error("--volumes failed. Please retry with --info for details.")}if((0,re.isTrue)(t.mountpoints)){const e=await(0,Z.mountpoints)();if(null!=e)return Me(e);console.error("--mountpoints failed. Please retry with --info for details.")}if((0,re.isTrue)(t.plan)||(0,re.isTrue)(t.licensing)){const e=(await(0,W.m)())[0],t=(0,ne.map)(e?.l,(t=>({email:t.sub,trial:t.trial,issued_at:t.iat,expires:t.exp,meta:e.meta})));return Me({plan:await(0,W.t)(),current_license:t})}if((0,re.isTrue)(t.suggestedLibraries))return Me(await(0,me.suggestedLibraryDirs)());if((0,re.isTrue)(t.volumesTtl))return Me({volumesTTL:await(0,fe.calcVolumesTTL)()??(0,X.volumeMetadataTtlMs)()});if((0,re.isTrue)(t.childEnv))return Me((0,w.childEnv)());const _e=(0,a.mkLogger)("info");if((0,re.isTrue)(t.loadLibrary)||(0,re.isTrue)(t.syncPaths)||I){const e=(0,k.libraryDataDirPosixFile)();if(null==e)return console.error("Error: please set up your library.");if(!await e.isDirectory())return console.error("Error: your library data dir, "+e+", is missing.");_e.info("Waiting for library to spin up...");const t=he.Library.instance();try{await(t?.ready)}catch(e){_e.warn("Failed to spin up library",e)}const i=(0,T.pathToDb)(e,"models");if(!await i.isNonEmptyFile())return console.error("Error: your library database, "+i+" is missing.")}if(I)return await(0,de.cleanup_)(),Me({cleanup:"OK"});if((0,re.isTrue)(t.syncPaths))return Me(await(0,ve.syncPathsForUI)());if((0,ie.notBlank)(t.isLibrary)){const e=await(0,E.whyNotLibraryDir)(t.isLibrary);return Me((0,ae.compactValues)({isLibrary:null==e,why:e}))}if((0,re.isTrue)(t.validate)){if((0,te.isEmpty)(i))throw new Error("--validate requires filenames");return H.Settings.validateVideos.envValue=!0,H.Settings.validateJpegImages.envValue=!0,H.Settings.validateRawImages.envValue=!0,Me(await Promise.all(i.map((async e=>[e,(0,ie.notBlankOr)(await(0,z.whyInvalidFile)(e),"OK")]))))}if((0,te.isEmpty)(i)){await(0,v.until)((()=>ee.CpuUsage.instance().busyPct()),{timeoutMs:2*se.secondMs,intervalMs:250});const e={systemInfo:(0,ae.fromEntries)((await(0,pe.systemInformation)()).map((({term:e,defn:t})=>[(0,c.asObjectKey)(e),t])))};return e.versionCheck={userAgent:await(0,Y.userAgent)(),...await(0,Y.checkVersion_)().catch((e=>({error:(0,C.errorToS)(e)}))),currentChannel:(0,Y.currentChannel)()},e.user_ids=(0,d.userids)(),e.group_ids=(0,d.groupids)(),e.username=await(0,d.username)(),e.paths={libraryDir:H.Settings.libraryDir.valueOrDefault,originalsDir:(0,k.libraryOriginalsDirPosixFile)()?.nativePath,systemSettingsFile:(0,G.systemSettingsFile)(),librarySettingsFile:(0,q.librarySettingsFile)()?.nativePath,libraryPreviewsDir:(0,k.libraryPreviewsDirPosixFile)()?.nativePath,librarySyncReportsDir:(0,k.librarySyncReportsDir)()?.nativePath,cacheDir:(0,D.cacheDir)(),logDir:(0,x.logDir)(),toolsDir:(0,R.toolsDir)()?.nativePath,osToolsDir:(0,R.osToolsDir)()?.nativePath,ffmpeg:await(0,V.ffmpegNativePath)(),sqlite:await(0,R.sqliteNativePath_)().catch((e=>"not found: "+(0,C.errorToS)(e)))},(0,re.isTrue)(t.health)?(e.healthSummary=await(0,N.getLocalHealthSummary)(),e.healthChecks=await Promise.all(B.HealthCheck.testResults())):(0,re.isTrue)(t.doctor)?(await(0,ye.libraryHealthCheckSetup)(),e.healthChecks=await B.HealthCheck.notOkResults()):e.healthSummary=await(0,N.getRemoteOrLocalHealthSummary)(),e.wrongPsEnvValues=(0,$.verifyPsEnvSettings)(),(0,re.isTrue)(t.loadLibrary)&&(e.libraryMetrics=(0,ae.fromEntries)((await(0,pe.libraryMetrics)())?.map((e=>[(0,c.asObjectKey)(e.desc),e.count]))??[])),e.volumesTTL=(0,_.fmtFullDuration)(await(0,fe.calcVolumesTTL)()),e.nonDefaultSettings=(0,ae.fromEntries)((0,ae.values)(H.Settings).filter((e=>e.hasValue())).map((e=>[e.name,e.humanValue]))),Me(e)}if(2===i.length){const e=L.PosixFile.for(i[0]),t=L.PosixFile.for(i[1]),r=await(0,m.mkAssetFile_)(e),s=await(0,m.mkAssetFile_)(t),n=[];if(null==r&&n.push("Failed to read "+e),null==s&&n.push("Failed to read "+t),(0,te.isNotEmpty)(n))return Me({errors:n});const a=(0,f.whyNotSimilarAssetFile)(r,s),l=null==a?"These two files will be aggregated into a single asset.":"These files represent different assets: "+a;let u,c;if(null==a){const e=(0,p.sortAssetFiles)([r,s]);u=e[0]?.nativePath,c=(0,o.zipPojos)(...await Promise.all(e.map(p.assetFileSortCriteriaPojo)))}const d={fileComparison:l,primary:u,a:await(0,be.info)(e,Se),b:await(0,be.info)(t,Se),cmpArr:c};return H.Settings.useImageHashes.valueOrDefault&&(d.imageHashComparison=(0,ae.omit)((0,j.compareImageHashes)(r,s),"a","b")),Me(d)}{const e=await(0,y.mapAsync)({name:"info",arr:i,f:e=>(0,be.info)(e,Se)}),t=(0,ae.fromEntries)(e?.map(((e,t)=>[t,e])));if(e.length>1){const e=(0,te.compact)(await(0,y.mapAsync)({name:"mkAssetFile",arr:i,f:e=>(0,m.mkAssetFile_)(L.PosixFile.for(e)).catch((t=>{console.error("Failed to read "+e,t)}))})),r=await(0,h.aggregateAssetFiles)(e);t.clusters=r.map((e=>e.map((e=>e.uri))))}return Me(t)}}()}catch(e){(0,F.onError)((0,I.toWrappedError)("Failed",{cause:e,fatal:!0}))}finally{await(0,g.exit)({reason:"done",status:0})}}},70750:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.info=void 0;const r=i(2023),s=i(75288),n=i(92356),a=i(4132),o=i(10408),l=i(64067),u=i(25015),c=i(98250),d=i(23872),h=i(95725),f=i(31216),m=i(46517),p=i(38336),g=i(83773),y=i(96593),v=i(27446),w=i(15465),b=i(39938),S=i(88491),P=i(61570),M=i(26588),_=i(49374),T=i(93445),D=i(69258),E=i(89452),k=i(9069),x=i(16630);t.info=async function(e,t){try{const i=c.PosixFile.for(e),o=await(0,w.readMimeType)(i);if(null==o)return{nativePath:i.nativePath,error:`Could not read mimetype for ${i.nativePath}`};if((0,u.isSidecarMimetype)(o))return{nativePath:i.nativePath,mimetype:o,error:"Skipping sidecar mimetype"};if(!await(0,v.isAssetFileMimeType)(i))return{nativePath:i.nativePath,mimetype:o,error:"Skipping non-asset file mimetype"};const h=i.parent(),C=await(0,s.mkAssetFile_)(i),F=t?await p.Predicates.explain(h,...(0,l.notExcludedDirPredicates)(h)):void 0,I=t?await p.Predicates.explain(i,...(0,T.libraryFileFiltersFor)(i,{validateFile:!0})):void 0,O=C.dominantColors?.filter((e=>null!=e?.color?.name)).map((e=>({rgb:e.rgbhex,name:e.color?.name,pct:e.pct}))),A=await(0,D.tagAsset)({primaryVariation:i,files:[],priorTagPaths:[],capturedAts:[],uris:[await i.uri_()]}),L=null==(0,k.modelDb)()?void 0:await new x.AssetFileFinder(i).prior(),R=await(L?.matchesFile()),N=await(0,M.thenCollect)(E.AssetFile.sameShaInLibrary(i),(e=>e.getNativePath())),B=await(0,y.readTags)(i),j=(0,d.whyRejectFile)(i,!0===_.Library.instance()?.isReadySync()?(0,T.libraryFileFiltersFor)(i):void 0),z=(0,P.compactValues)({...(0,a.omitModeData)(C),...(0,P.pick)(B,"tz","tzSource","errors","inferred","duration"),dirFilters:F,dominantColors:O,fileFilters:I,needsTranscoding:await(0,m.needsTranscoding)(i),pathsInLibrary:N,pathToLibraryAsset:(0,g.pathToLibraryAsset)((0,S.localToDate)(C.capturedAtLocal),i),priorAssetFile:L?.toJSON(),priorIsInSync:R,sidecars:(await i.existingSidecars()).map((e=>e.base)),tagResult:A,validFile:(0,b.notBlankOr)(await(0,f.whyInvalidFile)(i.nativePath),"OK"),variantSortCriteria:(0,n.assetFileSortCriteriaPojo)(C),whyExcludedDirectoryRecursive:await(0,l.whyExcludedDirectoryRecursive)(h),whyRejected:j});return(0,P.compactValues)({nativePath:i.nativePath,mimetype:o,...(0,r.sortedKeys)(z)})}catch(t){return{nativePath:(0,h.toNativePath_)(e),error:(0,o.errorToS)(t)}}}},30690:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),D=i(87748),E=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),O=i(89452),A=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=O.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,E.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,A.toAssetId)(this)}renderCaption(e){return(0,E.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,E.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,s=W,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),D=i(65642),E=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),O=i(11944),A=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),H=i(61570),q=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),Z=i(13222),X=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Z.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,H.assignAllFields)(this,(0,H.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=x.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,A.at)((0,A.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,A.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,E.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,s=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),s=i(75556);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),s=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),s=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},77910:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(53525),s=i(88491),n=i(75556),a=i(1724);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),s=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),s=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),s=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),D=i(1429),E=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),O=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,O.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,E.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,E.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,D.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,E.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,E.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,E.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),s=[];for(const n of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),s.push(e)}}return s}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,E.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),s=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,s.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const s=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=s)return void c().debug("applyOnce(): already done",{priorCompleted:s});const n=this.ops().insertOne(e),o=await t(n);return(0,r.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function D(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=D;class E extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),E.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??D(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:s.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=E.minCreatedAt(),t=E.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=E,E.$tableName="Progress",E.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),s=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),s=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),D=i(39784),E=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),O=i(14405),A=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,D.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),A.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),A.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(O.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,E.fmt)(e.length)+" of ")+(0,E.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(O.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(O.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),s=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const s=c.$tableName;this.dbl.runScript([`INSERT INTO ${s}(${s}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),s=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),s=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),s=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,s.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},16630:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const o=i(4866),l=i(7162),u=i(67654),c=i(46852),d=i(7383),h=i(39506),f=i(53525),m=i(98250),p=i(72461),g=i(31216),y=i(47874),v=i(43414),w=i(96593),b=i(11944),S=i(59694),P=i(39938),M=i(88491),_=i(66776),T=i(75556),D=i(30690),E=i(89452);t.isFileInSync=async function(e){return new x(m.PosixFile.for(e)).alreadySynced()};const k=new h.SerialLaterQueue;class x{constructor(e,t){this.file=e,r.set(this,void 0),s.set(this,new Set),this.alreadySynced=(0,d.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>a(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,d.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new E.AssetFile).updateFromFile_(this.file);return null==e?a(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,o.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,o.lazy)((()=>v.Settings.useImageHashes.valueOrDefault?(0,p.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,o.lazy)((()=>(0,c.thenMap)(this.imageHash(),(e=>(0,b.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,o.lazy)((async()=>{const e=await this.capturedAt_();return a(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,d.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,P.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return a(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return a(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,d.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,g.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtOrImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,d.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return a(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;a(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw a(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),n(this,r,(0,l.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f"),this.ctx=(0,y.forceContextOrSetting)(t)}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),a(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}a(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(){const e=await this.file.uri_();if(null!=e)return E.AssetFile.ops().findOneBy({uri:e})??E.AssetFile.ops().findOneBy({uri:this.file.fileuri()});a(this,r,"f").warn("byUri() uri is null",{file:this.file})}assetByNormalizedPathUri(){return(0,c.thenMap)(this.file.normalizedPathUri_(),(e=>D.Asset.findFirstByFile((t=>t.where("AssetFile.uri",e)))))}assetBySha(){return(0,c.thenMap)(this.file.sha(),(e=>D.Asset.findFirstByFile((t=>t.where("AssetFile.sha",e)))))}async assetByCapturedAtOrImageHash(){const e=await this.capturedAt_();if(null==e)return a(this,r,"f").throw("Cannot import, capturedAt is null"+f.InternalErrorFlag);if(v.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(E.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=v.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=E.AssetFile.query();return(0,T.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(M.secondMs,v.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,d.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)a(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(v.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void a(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const n=await this.dominantLabhashes();if((0,b.isNotEmpty)(n)){const t=e.localBoundaries({delta:4*s});if(null==t)a(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",n).orWhereIn("mode1",n).orWhereIn("mode2",n))));if(null!=e)return e}}return this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash))}))}async firstSimilarAssetByQuery(e,t){a(this,s,"f").size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(a(this,s,"f"))));const i=await this.firstSimilarAsset(E.AssetFile.ops().all(t));return null!=i&&a(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const n=(0,S.sortBy)(e.filter((e=>!a(this,s,"f").has(e.id))),(e=>[(0,_.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of n)if(null!=e){await e.getNativePath();const i=E.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const n=(0,u.whyNotSameAsset)(t,e,i);if(null==n)return a(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);a(this,s,"f").add(e.id),a(this,r,"f").debug("Contemporary assetFile not similar: "+n,e?.uri)}}}t.AssetFileFinder=x,r=new WeakMap,s=new WeakMap},97840:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),D=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function b(){const e=[],i=[];for(const r of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(r)){const s=await(0,v.nativePathToUriPath)(r);null==s?(e.push(r),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",r)):i.push(s)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",r);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await b()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),b=i(36310),S=i(65548),P=i(71766),M=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await S.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),s=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=s.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=s.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,r.leastBy)(s,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),b.Operation.markOpCompleted({name:b.OperationNames.forceRestartSync}))}function D(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function E(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,s.lazy)((async()=>{const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),r=await(0,t.getStaleCompletedAt)(),s=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:s===e.nativePath,status:D(e,r),isNext:e.nativePath===i?.nativePath,lastStartedISO:E(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:E(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const r=i(3874);async function s(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=s,t.posixFileToUriPath=async function(e){return s(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return s(e,(0,r.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),s=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,s.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),D=i(8199),E=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),O=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return O().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const A=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:A,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=O().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(s.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),s.info("vacuuming orphan tags..."),await L()}catch(e){O().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(A,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),O().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,D.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,E.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")},71017:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=82118);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/list.js b/bin/list.js index 7204061..05fc049 100755 --- a/bin/list.js +++ b/bin/list.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(74485),{decode:s}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=s(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),n=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),n=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:n}=i(74485),s=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,n,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:a?.length?a:void 0,version:e,purpose:l}:n}const u=o(n);return s(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),s=a(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},45112:(e,t,i)=>{const r=i(6113),n=i(16464),s=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=s(n,o,p,t),v=m(y,f);return a(n,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=s("v1.local.",r,a,t),v=m(g,p);if(!l(n,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=s(o,l,w,t,n),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=s("v3.local.",n,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:n}=i(35740);n||(n=e=>null!=e&&e instanceof r),e.exports=n},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const n=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(n*t);case"day":case"days":case"d":return Math.round(864e5*n);case"week":case"weeks":case"w":return Math.round(6048e5*n);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*n)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:n}=i(39084),s=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),n=i(97540),s=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=n(u,e,t,i,l),d=await r(a,c,o);return s(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),n=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:n}=i(45112),s=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=s(c,e,f,h,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),n=i(37794),s=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:n,V2:s,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v1.local"),{pre:s,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v1.local"),s=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=s(e,o);t=n(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),n=i(76331),s=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:n,encrypt:s,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),a=n(r.generateKeyPair),o=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:n})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=s(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),n=i(49172),{generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),n=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=n.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=n(e,a);t=o(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:n}=i(42421),{post:s}=i(97362),a=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v3.local"),s=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=n(t);const f=s(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v3.local"),s=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),n=i(58271),s=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:n,encrypt:s,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),a=i(45445),o=i(70067),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),n=i(25054),s=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=s(e,h),m=n(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),n=i(42417),s=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),n=i(5816),{generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:o,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=n(e,u),d=s(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),n=i(80094),{_checkPublicKey:s}=i(80244),{post:a}=i(97362),o=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await n("v4.public.",e,void 0,64,t,c);return a("v4",s,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),n=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(n.isProd?"":`-${n.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),n=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return _(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return _(e,t,((e,t)=>(0,h.gt)(e,t)))}function T(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function _(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function x(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=T,t.least=function(e){return T(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const n=[];for(const s of D((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of D((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await x(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const n=r(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),T=i(43414),_=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,_.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:n.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:T.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,_.commandTimeoutMs)(),minDelayBetweenSpawnMillis:T.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:T.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class n{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=n},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>n){const e=this.getFirst(s);null!=e&&(r=e,n=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let n=!(0,r.noColor)();function s(e,t){return i=>n?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){n=e??!(0,r.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),n=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),n=i(9678),s=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),n=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),n=i(4866),s=i(98250);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),n=i(40786),s=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),n=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),n=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){n(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),n=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),n=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?T():_()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function T(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function _(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=T,t.localePosix=_,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),n=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(n.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),n=i(74269),s=i(78109);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),n=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),n=i(51498);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),n=i(75556),s=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,n.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const n=r(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&n.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=n.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),n=(0,o.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),n=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,n]of(0,u.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,u.keys)(e))if(r[s]=t(s,e[s]),n++,(0,l.gt)(n,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),n=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function T(){return"fedora"===(0,t.osDistributionLinux)()}function _(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,n.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=T,t.isAlpine=_;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return x(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":x(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(T())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(_())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),n=i(39784),s=i(21142);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const n=i(5712),s=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),T=i(46852),_=i(46027),E=i(4586),D=i(17875),x=i(98462),k=i(25015),C=i(3955),F=i(51053),I=i(71663),O=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),A=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))O().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,l.isEmpty)(n))return O().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(n);if(null!=o){for(const n of r){const r=await n.readJson();if(null==r){O().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){O().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){O().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(O().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),s.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,n.pidExists)(r)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),n=t.getTime(),s={...e,cmd:r,startTime:n};return await i.writeJson_(s),O().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void O().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,T.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{O().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(x.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,_.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),n=i(7162),s=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const n=r(i(97742)),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),b=i(46852),S=i(69317),P=i(9288),M=i(51053),T=i(71663),_=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return _().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function x(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(T.PowerShell.instance().ended)return L();const e=await T.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?L():x(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],O))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[n.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),n.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return L(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>x(e)))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),n.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===n.default.pid))||r.push({pid:n.default.pid,start:new Date(v.StartTs),cmd:"node "+n.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),n=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),n=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...n)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=n,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new a.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return n.promise}(...n)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),n=i(82798);function s(e){return e instanceof a?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(70612)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>_.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let T=!0;const _=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||_().has(e))return;_().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),T)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;T=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),n=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,n.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const n=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return n.setShim=e=>{i=e},n.hasShim=()=>null!=i,n}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),n=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,n.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),n=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),n},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),n=this.valueOf(this.store[r]);if(e===n)return{found:!0,index:r};e>n?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),n=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),n=i(18991);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(n+"\n"),(0,o.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+n+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function T(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=T;const _=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=_.exec(T(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function x(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,a),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(s,(()=>n.push(i)))})),n}function S(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const T=/[^\da-z]+/gi;function _(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(T,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,n-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=_,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:_(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),n=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,n,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,r,"m",n).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),n=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,n.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(70612)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[s]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const n=t();return null!=n&&this.set(e,n),n}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",n).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const n=i.deref();null==n?a(e,r,"f").delete(t):yield n}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const n=i.deref();null==n?a(e,r,"f").delete(t):yield[t,n]}}()}[(r=new WeakMap,i=new WeakSet,s=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,n=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),n=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),n=i(66776),s=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,n,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...n,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,n.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>T(e*t)))}function T(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function _(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=T,t.mtime2sort=_;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,n.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function x(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const n=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:_(n),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,n.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=x(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=x,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(92332)),s=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),T=i(61570),_=i(26588),E=i(46234),D=i(21669),x=i(7162),k=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,x.mkLogger)("async.Deferred")));class O{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new n(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,T.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,_.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,_.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=O,n=O,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],n.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}},r=new WeakMap,n=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=r.isTest?e:e||n}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,n.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,s,0,"f"),h(this,n,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,n,"f")?void 0:Date.now()-d(this,n,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,n,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),n=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let n,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:n):(s=!0,n=(0,r.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>n,o.force=async()=>(await n,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),n=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function T({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(n)?(0,d.thenOrTimeoutError)(i(a),n):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((n=Math.round(n??(0,w.maxCpus)()))<=1)return T({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=n?b.PermissivePromises:new b.Promises(i,(()=>n))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(n);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=T,t.mapAsyncSerial=async function(e){return(await T(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const a=await i(n,s);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function T(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return T(e,Date.now()-i),r},t.pushTime=T,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,n,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),n=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,n.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),n=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,s.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],T=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],_=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:T),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(n.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:x({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function x({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,o.compactValues)({...(0,t.sanitizedEnv)(),..._(),...i?(0,f.childProcLocale)():{},...E(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(n);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(n),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return n}t.childEnv=x},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(17718)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),T=i(46027),_=i(49379),E=i(79141),D=i(83837),x=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function O(e,i,r,n=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,T.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&o.push((0,T.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),o.push((0,T.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function A(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,x.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),O(n.default.execFile(e,t,s),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=A(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||n?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const T=y.join("");(0,l.notBlank)(T)&&v.push(new Error(T)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const x=i.isIgnorableError??_.isIgnorableError,k=v.filter((e=>!0!==x(e)));if(k.length>0)throw 1===k.length?k[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:T}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),O(n.default.spawn(e,t,s),e,t,i)},t.execFile=A,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),n=i(43414),s=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),T=i(17875),_=i(79141),E=i(45512),D=i(7162),x=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new _.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,n,"f")||a||(this.lastError=s,(0,T.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,x.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,T.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,T.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const n=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=n?a.join("$library",i.posixPathFrom(n)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),n=i(97742),s=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,n.exit)(0)})),e.parse(n.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),n=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,n.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),n=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(97742)),s=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(n.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),n=i(11944),s=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),n=i(82041),s=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),n=i(11944),s=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,n.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),s=b(r);return null!=r&&null!=s&&((0,n.pushUniq)(s.closeLabhashes,e),(0,n.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(r))),s})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),n=i(11944),s=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(_(T(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,n.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let n=0;ne>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function T(e){const[t,i,r]=v(e),n=(t+16)/116,s=i/500+n,a=n-r/200,o=s*s*s,l=a*a*a,u=o>S?o:(116*s-16)/P,c=t>8?Math.pow(n,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function _(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=T,t.xyz2rgb=_,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function x(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,r]=(0,f.clampRGB)(e),n=Math.max(t,i,r),s=n-Math.min(t,i,r),a=s?n===t?(i-r)/s:n===i?2+(r-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),n?s/n*100:0,n/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,r]=e,n=(200-i)*r/100;return[t,n>0&&n<200?i*r/100/(n<=100?n:200-n)*100:0,n/2]}function I(e){const[t,i,r]=e,n=i*(r<50?r:100-r)/100;return[t,n>0?2*n/(r+n)*100:0,r+n]}function O(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,n=Math.floor(t),s=r*(1-i),a=r*(1-(t-n)*i),o=r*(1-(1-t+n)*i),l=n%6;return(0,f.clampRGB)([255*[r,a,s,s,o,r][l],255*[o,r,r,a,s,s][l],255*[s,s,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(D,e,(()=>x(e,t))):x(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return O(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=O,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),n=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,s]=e,[a,o,l]=t,u=i-a,c=r-o,d=s-l,h=(0,n.sqrt)(r**2+s**2),f=h-(0,n.sqrt)(o**2+l**2),m=(0,n.sqrt)(c**2+d**2-f**2);return(0,n.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,n.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,n.sqrt)(d**2+h**2))/2,m=.5*(1-(0,n.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,n.sqrt)(p*p+l*l),v=(0,n.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const T=2*(0,n.sqrt)(y*v)*Math.sin(M/2),_=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+b:(D=(w+b)/2,D-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const x=(_-50)**2,k=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*x/(0,n.sqrt)(20+x),F=1+.045*E,I=1+.015*E*k,O=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),A=2*(0,n.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*O)*A;return(0,n.sqrt)(Math.pow(S/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(T/(o*I),2)+L*P/(a*F)*T/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),n=i(75556),s=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,n.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,n.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,n.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,n.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,n.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,n.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=T[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function x(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,n.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{..._,seed:e}),n=k(r.centroids,f.length);if(n.lengtht&&x(g-1);const s=n.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const n=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,n)));null!=s&&(0,l.times)(r,(()=>t.push(s.value)))}return t.p84}(s);return{...r,centroids:s,description:{kIn:g,kOut:r.centroids.length,kMerged:n.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),O=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(O),pixelCount:f.length}),{dominantColors:O,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],T={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},_=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:T[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const n=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(n))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=n));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:n,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:n,minK:t,retries:r,pixelCount:e.length,filteredCount:s.length}),E({labs:e,minK:t,thresh:.75*n,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;x(e);const s=e.size,a=(0,n.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:s,pixelCount:i,pctOmitted:l})}}function x(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,n]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:r}):(e.delete(r),e.incr(a.labhash,n))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const n=t/100;return(0,s.sortBy)(r.filter((e=>e.size>n)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{_.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=x,t.mergeNearCentroids=k},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),n=i(75556),s=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,n.within)(0,100,e[0])&&(0,n.within)(-110,110,e[1])&&(0,n.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const n=(i.stdDev??0)+(r.stdDev??0),s=n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),n=i(61570),s=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,n.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,n.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),n=i(65113),s=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,n.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),n=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),n=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function T(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function _(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),x(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function x(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=_(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,a.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=T,t.toDated=function(e){return T(e)?e:void 0},t.mapDated=function(e,t){return T(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=_,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=x,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),x)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=x(e)),r??(r=x(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),n=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),n=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),n=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:n,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),n=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),n=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),T=i(64455),_=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return n.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function x(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(n=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),a=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${E(s)}:${E(a)}`},t.toExifDateTime=x,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):x(e,(0,_.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function O(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?n.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,_.hasZone)(t)?C:k):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(O(e,t),l.dayMs)},t.diffMillis=O,t.closeTo=function(e,t,i){return(0,u.mapOr)(O(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(r+1),l=(0,_.getZoneName)(e),u=l===(0,_.getZoneName)(t)?l:void 0,c=n.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,_.hasZone)(e)},n=(0,M.normalizeZone)(t);if(null!=e&&null!=n&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(n,r):x(e)?.setZone(n,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,_.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),T=i(55170),_=i(45161),E=i(50140),D=i(82701),x=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:A.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return A.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return A.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=O({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,T.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,T.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function O({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,T.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:T.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of A.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=O;class A{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",s).call(this))),a(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;_.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=O({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=A,r=new WeakSet,n=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,x.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},A.instance=(0,u.lazy)((()=>new A));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return _.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,x.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),n=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(a(e))||(0,n.gt0)(o(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),n=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),n=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?T(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(T(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return T(Date.now()-e,t)}function T(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),n=i(59694),s=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,n.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),n=i(4866),s=i(92507),a=i(43414);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const T=/\b(?Z|UTC|GMT)\b/,_=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,x=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),T,new m.RegExpEscaped("|"),_,D,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,O=(0,s.lazy)((()=>(0,m.concatRegexp)([I,_,x,m.RegExpOptional.from(k)])));function A(e){return F(O().exec(e))}t.ianaZoneToOffsetMinutes=A,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=A(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),T=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=x(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function x(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof n.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=n.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return _().includes((0,v.datedToMillis)(e))?"bad date (via millis)":T().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=x,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function O(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function A(e,t,i){return(0,u.gt0)(i)&&n.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||O(t,e))&&(!(0,u.gt0)(i)||A(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=O,t.validDay=A,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),n=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),n=i(1629),s=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+s.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,n.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),n=i(82341),s=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,s.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,n.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),n=i(7162),s=i(61253),a=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,s.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),n=i(49379),s=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+s.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+s.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),n=i(85590),s=i(11944),a=i(61570);function o(e){return null===e||(0,s.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,n.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),n=i(19658),s=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(s.Settings.dbBatchSelectSize.valueOrDefault*(n.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),n=i(75556),s=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,n.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let n;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();n=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/s.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:n});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*s.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),n=i(75556),s=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,n.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,s.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),n=i(65886),s=i(76915);t.sqliteFiles=function(e){return[e,...n.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[s.SqliteExt,...[...n.SQLiteSuffixes,"-shm"].map((e=>s.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),n=i(75556),s=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,n.isNumber)(e))return e.toString();const t=(0,s.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,s.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let n;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),n=i(24603),s=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,s.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,n.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,s.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,n.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),n=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),T=i(58676),_=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function k(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,_.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,_.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),n=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),n=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),n=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),n=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),n=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),n=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),n=i(82798),s=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,n.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),n=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function T(e){return y(M(e))}async function _(e){return y((0,n.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await T(t),await _(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=T,t.setupLibraryDbDir_=_},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),n=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!n.isProd&&!(0,s.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),n=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(87561)),s=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(n.default.readFileSync(r)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(s))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),n=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const a of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const a=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),n=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(S(e)),r=t?.maxLen??400,n=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,n)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),n=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),n=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),n=i(88491),s=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),b=i(6231),S=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class T{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=T,T.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new T(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),n=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,n.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class n extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=n},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),n=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),n=i(87489);function s(e,...t){return n.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,r.lazy)((()=>s("exit")))},80313:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),n.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,r,"f").get(e);return null!=a&&(a.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),n=i(4866),s=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,n.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let n=!1;t.isSyncing=function(){return n},t.setIsSyncing=function(e){n!==e&&(n=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),n=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,n.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,n.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),T=i(38625),_=i(88491),E=i(43383),D=i(24603),x=i(16475),k=i(1429),C=i(87748),F=i(21040),I=i(66776),O=i(75556),A=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),ne=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,O.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,O.isNumber)(e.pid)&&(0,T.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=_.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),n=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=n,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),_.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let n=!1;if((0,P.isEmpty)(i))return;const s=be((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),n||(n=p(this,r,"m",f).call(this,e));n&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,O.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,A.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},n=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?n.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(n.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,n),this.save(),n)}}t.SharedState=Se,n=Se,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*_.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:_.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,s,"f"),b.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:n}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(n)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(n,n,"f",u)),ce.Settings.cacheDir.watchLater(p(n,n,"f",u)),ce.Settings.sharedStateDir.watchLater(p(n,n,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,ne.nativePathsEqlSync)(e,n.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(n.instance()),n.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,x.shortStack)());p(n,n,"f",l).call(n);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new n(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),n=i(79015);let s=!1;(0,r.later)((()=>(0,n.ee)().on("updateReadyToInstall",(()=>s=!0)))),t.isUpdateReadyToInstall=function(){return s}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(87561)),s=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const a=n??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),n=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),T=i(92585),_=i(39938),E=i(88491),D=i(24603),x=i(1429),k=i(87748),C=i(66776),F=i(75556),I=i(61570),O=i(98510),A=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),ne=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,_.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new Se(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(_.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,A.pad2)(t+1),(0,A.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,O.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,T.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*E.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),n=i(17310),s=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(n.ExtTypes.Video),t.isAssetFileExtension=o(n.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),n=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),n=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(49411)),s=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),n=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,n.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const n=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(n);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(n,(async(e,i)=>{g().trace("callback",{nativePath:n,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:n}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(n,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,n.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class T{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new T(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await o.stat(t);return new T(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return T.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new T(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>T.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new T(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=T},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),T=i(85943),_=i(82341),E=i(20902),D=i(9483),x=i(51053),k=i(38336),C=i(51776),F=i(43414),I=i(77390),O=i(98462),A=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:O.BaseFile.for(e),n=V.test(t)||r.isDirectorySync(),s=(0,R.native2posix)(r.nativePath),a=n?(0,m.ensureSuffix)(s,"/"):s;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",n).bind(this)):{}}}r=new WeakSet,n=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((x.isWin?"*":"")+"/"+t.s+"/",t.desc));if(x.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}x.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const n=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===n.length&&e.push(new U(`**/${t}/${n[0]}/`,r)),n.length>1&&e.push(new U(`**/${t}/(${n.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:ne,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[n,s]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:n,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return k.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function ne(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function se(e){return(0,S.thenNot)((0,A.isHidden)(e))}function ae(e){return!(0,T.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,_.libraryDirPosixFile)(),(0,_.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),n=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,n.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),n=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,n.pick)(await(0,r.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),n=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,n.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(a)?void 0:{ext:a,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),T=i(92332),_=i(11944),E=i(37609),D=i(88491),x=i(24603),k=i(19067),C=i(66776),F=i(75556),I=i(23175),O=i(20636),A=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),w(this,n,"f",s)+1),"f",s),(0,_.compactBlanks)([q.TokenRadix.encode(w(this,n,"f",s)),N.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return w(this,n,"f",o).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=w(t,n,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(n,n,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,_.filterInPlace)(w(n,n,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),n=i(44726),s=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),T=i(91641),_=i(17354),E=i(79015),D=i(3955),x=i(8177),k=i(43414),C=i(91464),F=i(37086),I=i(59873),O=i(95725),A=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,x.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,x.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,O.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:T.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),n.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,n,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,n,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,_.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,n,"f")});const e=c(this,n,"f"),i=await(0,A.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,n,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,n,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,O.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,n,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,n,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),n=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(87561)),s=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44470)),s=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(6005)),s=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),n=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),n=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),n=i(66776),s=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),n=i(44726),s=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),n=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,n.toNativePath_)(e),r=(0,n.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,n.toNativePath_)(e))===await(0,r.actualPath_)((0,n.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function T(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const r=await Promise.race([_(e,t),D(e,t)]);return t.halt(),r}(t.nativePath)))}async function _(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,T)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=T},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44470)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return _((0,y.posix2native)(e))},t.extname=function(e){return _(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function _(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function E(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(g.isLinux?r===n:(0,m.equalsIgnoreCase)(r,n))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=_,t.parentBasename=E,t.grandParentBasename=function(e){return E(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),F([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("โ€ฆ"),F([...n,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=_(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function T(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function _(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...T()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([..._(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,n,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),T=i(66776),_=i(75556),E=i(61570),D=i(20636),x=i(49049),k=i(17078),C=i(82798),F=i(13779),I=i(7162),O=i(14889),A=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),ne=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:O.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,A.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,A.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,T.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,T.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===x.PS_LIBRARY_SCHEME?1:t.scheme===x.PS_LOCAL_FILE_SCHEME?2:t.scheme===x.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,A.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,A.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,T.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:n,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*n,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,A.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,_.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,A.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,D.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:O.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(O.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,_.clamp)(O.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,T.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,A.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,_.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,T.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,T.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),n=i(39938),s=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function T(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function _(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,n.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function x(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,n.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,n.notBlank)(t.Make)&&(0,n.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function O(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function A(e){return[...O(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:T},{notVideoTooLong:_},{notRejectedRating:D},{notExcludedKeyword:x}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??A(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=O,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...O(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...O(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...O(e))},t.expensiveFileFiltersFor=A,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const n=r(i(49411)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>n.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(n.default.join((0,t.execDir)(),"resources"),n.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=n.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),n=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,n.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),n=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,a,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),n=i(51081);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function _(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=E(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===h.Timeout&&(0,p.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await _(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?_(e):E(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=_,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const n=r(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return n.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),n=i(43414),s=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>n.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),n=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const n=r(i(87561)),s=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(P(r),P(n));if(null==s||s>1)return"unmatched "+i+": "+r+" โ‰  "+n}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const n=r(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),n=i(6314);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),T=i(8177),_=i(38307),E=i(91641),D=i(95557),x=i(57510),k=i(82341),C=i(35796),F=i(10408),I=i(53525),O=i(18849),A=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,T.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,k.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,n,s,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=n,this.elapsedMs=s,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,A.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),r.add(this),n.set(this,void 0),s.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,n,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,O.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),n={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},s=(0,h.unparse)([n],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(s+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const n=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await r(),a=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:s}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-n,...s,state:a}),s}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-n}),r}}get output(){return l(this,s,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,s,"f");return u(this,s,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,n,"f")}}t.SyncReport=$,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,n,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,x.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,n,"f").nativePath),this.logger.info("Opening new report: "+l(this,n,"f")),M.isTest&&(0,_.stdoutWrite)({syncReport:l(this,n,"f").nativePath},!1),u(this,s,(0,d.createWriteStream)(l(this,n,"f").nativePath),"f"),l(this,s,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,s,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),n=i(43947),s=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function T(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function _(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await T(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=T,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await _(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await _(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=_},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),n=i(14889),s=i(95725);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),n=i(34996);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44470)),s=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),n=i(79403),s=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),T=i(16475),_=i(77125),E=i(66776),D=i(23175),x=i(44726),k=i(20636),C=i(90957),F=i(39784),I=i(82798),O=i(13779),A=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),Z=i(18295),X=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,n,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,n,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,n,"f",l).push((0,x.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,n,"f",l).toA()}static addLoadingMsg(e){v(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,n,"f",h).entriesByCountDesc()}),(0,E.map)((0,O.leastBy)(e,(e=>[v(this,n,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,n,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return v(this,n,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,_.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=n.summary();if(t.settledCountv(n,n,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>n.onResultChange(),onError:()=>n.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,O.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,n=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,n,"f",s),(e=>!e.isPending)),v(this,n,"f",s)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Z.summarizeHealthChecksSync)({errors:v(this,n,"f",l),skipPending:v(this,n,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,n,!0,"f",u),t.state!==v(this,n,"f",c).last?.state&&v(this,n,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=n.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,x.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new A.BoundedList(10)},u={value:!1},c={value:new A.BoundedList(10)},d={value:new A.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(n,n,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(n,n,"m",m).call(n))),Q.resetDebounced=(0,N.debounce)((()=>n.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),n=i(77125),s=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),n=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(70612)),s=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),n=i(88491),s=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),n=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),T=i(4416),_=i(47874),E=i(43414),D=i(96593),x=i(95011),k=i(49312),C=i(36810),F=i(87062),I=i(80870),O=i(14489),A=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,n.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const n=i.sha??await r.sha();if(null!=n)if(!0!==await(0,t.isBadSha)(n))try{return await this._build(r,i)}catch(t){e.push(t),L().set(n,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,A.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:n,width:a,height:o,sha:l,mimetype:u}=t;if(null==n||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,x.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:n,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,s.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),n=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,x.equivalentFitSizes)(r,n)){const a=(0,x.fitSizes)(e,e.mimetype),o=(0,s.diff)(r,n);if((0,s.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const n=new T.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,x.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const s=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),n.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,s=t.outputSize(p??S);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),n.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),n=i(57743),s=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,n.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),n=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:n,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:n,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,n.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,n.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),n=(0,p.splitEvery)(i,3);this.basename=n.pop()+"-",this.parent=e.join(...n)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,r,"m",n).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const n=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=n,await this.writeInfo(t)),n}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,n=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const n=r(i(57441)),s=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;in?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:n.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:n.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),n=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),n=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),n=i(57743),s=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,n.dmegapixels)(a)-(0,n.dmegapixels)(l)>2.5)&&(l=a,r.push([a,s])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),n=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),n=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),n=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),n=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const n=r(i(57441)),s=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),T=i(13378),_=i(27446),E=i(68107),D=i(37251),x=i(34928),k=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function O(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,x.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const s=(0,x.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,_.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:n.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,n.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,n.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,_.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function A(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,T.shim1)({name:"img.imageHash",cache:I,impl:O}),t._imageHash_=O,t.isImageHash=A,t.toImageHash=function(e){if(null!=e){if(A(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(A(t))return t}}},t.HashDim=8},36810:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return s(this,r,"f",n).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,r,"f",n).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,r,"f",n)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(r,r,"f",n).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,n={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),n=i(11944),s=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,n.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,s.assignFields)(i,r.asExifTag()));const n=i?.exposureSettings;null!=n&&(delete i.exposureSettings,i.FocalLength=n.focalLength,i.FNumber=n.aperture,i.ExposureTime=n.shutterSpeed,i.ISO=n.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const n=r(i(57441)),s=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:n.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:n.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(r.map(c)),diffHash:(0,s.flatten)(r.map(d))}}},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),n=i(66776),s=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,n.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),n=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),n=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,a]=e.split("\t"),o=(0,n.toGt0)(s),l=(0,n.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),n=i(57743),s=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const n=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:n,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,n.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,n.fmtDim)(i)} is too small for ${(0,n.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const n=i(889),s=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),T=i(96593),_=i(27446),E=i(84685),D=i(15465),x=i(68107),k=i(53719),C=i(59387),F=i(34928),I=i(71923),O=i(49312),A=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{s.default.simd(M.Settings.enableSIMD.valueOrDefault),s.default.cache(M.Settings.enableVipsCache.valueOrDefault),s.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,T.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof n.BinaryField))return;const l=o.bytes(0,T.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const s=await(0,D.readMimeType)(e);if((0,u.blank)(s))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,x.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,_.isVideoMimeType)(s),S=(0,_.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),A=(0,h.lt)(C,1),L=(0,_.isSharpMimeType)(s)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||A||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:A,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,s=await(0,T.readRawTags)(e,i);if(null==s)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof n.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,s,t,k,C)))}}}(0,_.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(s)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const n=await(0,w.time)("img.read."+i.desc,i);if(null!=n)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:n.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...n};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),n=i(88491),s=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=n.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*n.secondMs},p1:{x:20*o.MB,y:12*n.secondMs}},p={p0:{x:11*o.MB,y:12*n.secondMs},p1:{x:26*o.MB,y:24*n.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,n=(0,f.commandTimeoutMs)(),s=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+n+s+c+d),dbMs:i,tagMs:n,copyMs:s,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,s.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const n=r(i(57441)),s=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),T=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void T().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=T().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&T().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const _=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return _().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:_,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(T().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))T().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,n.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,n.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),n=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),n=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),T=i(43649),_=i(6667),E=i(49586),D=i(43414),x=i(68567),k=i(27947),C=i(96593),F=i(27446),I=i(84685),O=i(68107),A=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),n=D.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,n))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,x.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,T.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,O.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),h=null==d?void 0:await(0,L.dimensions)(n);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:h}),n.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,A.commandTimeoutMs)()}),n.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,n.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const r=j("transcode",e),n=$.get(t.nativePath);if(null!=n&&!(0,s.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:n.name}),n.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),n=(0,k.extractDurationSec)(r),s=(0,k.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,n={src:e,...V(e,d)},s=J(o,n.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,_.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(n.width=(0,u.roundEven)(e.width),n.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));n.dest=i,n.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(n));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),T=i(5023),_=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,x=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function k(){x.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(x(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await x.prior()??x.refresh()},t.isFFmpegSupported=async function(){return null!=await x()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...O(t),...C(t),"-threads",(0,u.toS)((0,T.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,T.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),n=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,n.lazy)((()=>(0,r.toGt0)(s.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),n=i(88491),s=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:n.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:n.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),T=i(33185),_=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return _().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],x=["-o","1"],k=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return _().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(_().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...E,...D,...x,...v,...k,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*s.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};_().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),O=[];function A(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,T.isIgnorableValidationError)(i))_().info("dcraw_emu(): warning",{src:e,msg:i});else{_().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});O.push(r)}}I.on("error",A),I.stderr.on("data",A);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,n.isNotEmpty)(O))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:O,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),n=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),n=i(43414),s=i(69060);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),n=i(11944),s=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),n=i(59694),s=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),T=i(79015),_=i(98462),E=i(43414),D=i(10508),x=i(33501),k=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,k.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function A(e,i,r,n){try{return(0,s.blank)(e)?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=A,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await A(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>_.BaseFile.for(e))),r=(s=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,n.sortBy)(s.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,T.ee)().on("clearCache",(()=>t.m.unset())),(0,T.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),n=i(4866),s=i(39938),a=i(10508);t.l=(0,n.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===n));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,s.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),n=i(39938),s=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),T=i(46573),_=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const x=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,a.defer)((()=>(0,m.thenMap)(k(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(F)))}async function O(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function A(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void x().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,_.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,T.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,O,A,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return x().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),n=i(88491),s=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),b=i(92781);function S(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*n.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),n=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),n=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),n=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,n.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),n=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),n=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?n(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),n=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),n=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),n=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>n(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),n=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),n=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),n=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),T=i(10408),_=i(57400),E=i(3955),D=i(43414),x=i(71951),k=i(85352),C=i(81647),F=i(95976),I=i(9483),O=i(98968),A=i(53208);function L(e){const t=(0,x.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await _.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,O.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,O.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,O.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,O.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await _.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,A.readLogEntries)(e,{start:r,end:i}),(e=>(0,O.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,T.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),n=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),T=i(93033),_=i(40374),E=i(83837),D=i(43414),x=i(74269),k=i(85352),C=i(81647),F=i(95976),I=i(48924),O=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class A extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,n,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,O.recentLogEntries)()),(0,O.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=A,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,T.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,_.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),n=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),n=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,n.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),n=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),n=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),T=i(81026),_=i(27998);t.setupLogger=(0,n.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new T.LogWriter(e));const n=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&n.push(y.ConsoleLogger.instance()),(0,s.map)((0,b.logBroadcaster)(),(e=>n.push(e))),l.rootLoggers.set(n),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,n.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new _.PlaintextLogFormatter)}));const E=(0,n.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,n=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),n=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):r[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),n=i(89965);t.kmeans=function(e,t,i){const s=n(e,t,i);return{...s,centroids:(0,r.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return n(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),n=i(75556),s=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const n=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=n;t(0,n.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,r){const s=new a.Average;return l(t,i,r,(t=>(0,n.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,r){const s=[];return l(t,i,r,(t=>(0,n.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const n=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(n,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,n=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,s.leastIndex)(n)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,n=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,s.greatestIndex)(n)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,n.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),n=i(88491),s=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[n,s,a,o,l]=(0,t.factors)(e),u=(n*i*i+s*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[n,s,a,o,l]=(0,t.factors)(e);return`(((${n}*${i}*${i}+${s}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,n,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,n/o,l/u,c/h].map((e=>(0,s.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:n.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),n=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),n=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},76474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),n=i(3331);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),a(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),n=i(39938),s=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,n.mapNotBlank)(e,(e=>(0,n.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),n=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),n=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,n.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),n=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),n=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),n=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,n.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),n=i(4866),s=i(82798);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),n=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(70612)),s=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),n=i(44726),s=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,n.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),n=i(11944),s=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],n=[];for(const a of t)for(const[t,o]of(0,s.entries)(a)){const s=await o(e);!0===s?i.push(t):!1===s?r.push(t):n.push(t)}return{accepted:i,rejected:r,notApplicable:n}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:s,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,n.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),n=i(86780);class s{static firstFalse(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i))if(!1===n(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i))if(!0===n(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i)){const i=n(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,n.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),n=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),n=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),n=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),n=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,n.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),n=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),T=i(43414),_=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",T.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,s.mapNotBlankOr)(T.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:T.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,_.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),T.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(T.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,_.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),n=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),n=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),n=i(61570),s=i(84253),a=i(43414),o=(0,s.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,n.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,n.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),n=i(39784),s=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=s.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),n=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(g.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],T={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},_={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?_:T;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),n=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),n=i(4866),s=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,n.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const n=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),n=i(63774);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),n=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,n.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,n.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,n.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,n.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),n=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),T=i(29393),_=i(94794),E=i(7560),D=i(45005),x=i(20902),k=i(6565),C=i(80534),F=i(86613),I=i(15203),O=i(51053),A=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),ne=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>O.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!O.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>O.isMac?"100ms":O.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:_.RepairModes,defaultValue:_.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:O.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,A.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>O.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,A.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(O.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ne.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(n.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(n.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,x.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),n=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>n.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:n.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),T=i(10408),_=i(79015),E=i(98462),D=i(98250),x=i(38846),k=i(23830),C=i(84161),F=i(44911),I=i(43414),O=i(95699),A=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(A.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",H),(0,_.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let n="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(n,i),j().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(n),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(j().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"old"}),await n.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Z(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,T.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,n.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,x.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),n=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),n=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),n=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),n=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),n=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),n=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,o.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),n=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),n=i(91464);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),T=i(50140),_=i(68074),E=i(54809),D=i(64455),x=i(60299),k=i(3955),C=i(95725),F=i(63410),I=i(9483),O=i(43414),A=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,_.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,_.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,_.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,_.datedToLocal)(i.minus(t)),end:(0,_.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],n=r;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||L.OverrideUTCZoneTags.includes(n))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,_.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:a}),a}function q(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,_.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=n("tags",U(t,O.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??n("tags",U(t,O.Settings.capturedAtTagsFallback.values))??(s?void 0:n("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:n("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",q(e,t)))??(s?void 0:n("path",H(e)))??(O.Settings.useStatToInferDates.valueOrDefault?n("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),n=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(889),s=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),T=i(23595),_=i(84593),E=i(21084),D=i(98250),x=i(95725),k=i(76531),C=i(7162),F=i(76474),I=i(19658),O=i(2023),A=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),Z=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),ne=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,A.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,x.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),n=await e.sidecar(),s=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void se().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;se().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(n,"tz","tzSource",...L.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,X.normalizeMimetype),...n},o=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(n))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,O.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(n))),(0,f.assignFields)(a,n),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,O.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,T.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=o?(0,Z.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Z.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,o);if(null==h)return void se().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,_.eqlAsync)(e.sha(),t.sha())||await(0,_.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,x.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,x.toNativePath_)(e),["-"+t]);return(0,O.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[n,s]of(0,f.entries)(t)){const t=await me(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),n=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:n}),await le().write(r.nativePath,n,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[a])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,h.toS)(n)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var n;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function T(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function _({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),a=n(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=T,t.findInequalFields=function(e,i){const r=T(e),s=T(i);if(null==r||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=s[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,n.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>_({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>_({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>_({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>_({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),n=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),n=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),n=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),T=i(95725),_=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>x({action:e,key:t,value:i})))}function x({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=x,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function O(e,i,r){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,T.toNativePath_)(e),a=await(0,E._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,a.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=D(t.Actions.infer,r),s=(_.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return _.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),O(i,n,s)},t.ensureHistoryRecords=O},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,l.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),n=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),n=i(25861),s=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new n.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function T(e){return Array.isArray(e)&&e.every(T)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(T))}function _(e){if(null==e)return[];if(Array.isArray(e)&&e.every(T))return(0,h.flatMap)(e,_);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,_).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=T,t.parseKeywordStruct=_,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(T(i)?t.push(..._(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,n.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),n=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,n.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,n.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const n=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>n.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,n.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:n}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)n.push(`Revision@${i.createdAt}`),(0,s.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){n.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,s.remove)(e,t)}return{value:e,source:n}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),n=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),n=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),n=i(75556),s=i(43414);function a(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),n=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),n=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),n=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const s=S(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const n=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),n=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(n.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(n.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),T=i(21084),_=i(98250),E=i(75123),D=i(95725),x=i(9483),k=i(43414),C=i(96879),F=i(69301),I=i(65642),O=i(96593),A=i(17310),L=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,O.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:x.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new T.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(A.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),n=(0,D.findFileIndex)(e,r);if(n<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(n-2*t,n),r.slice(n+1,n+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,O.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),n=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,n.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,n.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),n=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(n,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return _(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new S(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===r&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new S(r,n,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(_(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=_(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function T(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?T:M;let r="";const{scheme:n,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=_;const x=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(x)?e.replace(x,(e=>D(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),n=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),n=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),n=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?a.join(t,...n):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),n=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),n=i(39036);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),n=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),n=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),n=i(55412),s=i(46573);t.currentVolumeRoots=(0,n.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,s.volumes)()){t.push(i.mountpoint);const n=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=n&&e.push(n)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),n=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await O()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const T=/([a-z]+)(?::\\)?/i;function _(e){return e?.match(T)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(_(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(_(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function x(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(_(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function O(){const e=(0,n.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,o.flatten)(t).map(x)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,n.compact)((0,o.flatten)(r).map(I)),l=(0,n.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=O},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),T=i(55412),_=i(62255),E=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,_.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await x(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,n.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,T.setupVolumeTTL)(t.gioVolumes)));const x=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),n=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...n,...s},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),n=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),T=i(76531),_=i(51053),E=i(43414),D=i(39206),x=i(36736),k=i(62255),C=i(49829),F=i(10609),I=i(53719),O=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function A(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){A(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(A),E.Settings.scanPaths.watchLater(A),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,x.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,T.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{x.gioVolumes.unset(),A()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:x.GioCommand,args:x.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(x.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function T(e){return!y.Settings.excludedFilesystemTypes.has(e)}function _(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=T,i=_){if(g.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=E,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),n=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),n=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),n=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>_())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function T(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=T;const _=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?T():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),n=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function T(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function _(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=_(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(T(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=T,t.toVolumeUUID=_,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(70612)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),T=i(91710),_=i(14889),E=i(91464),D=i(46852),x=i(37121),k=i(1629),C=i(14195),F=i(42648),I=i(29405),O=i(20902),A=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),ne=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),se=n.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:se}))),s=new Map;for(const e of n)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const n=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return ne().debug("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function ge(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,U.friendlyname)(e);return(0,D.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,x.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,A.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,T.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,x.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,A.onError)("Timed out getting local volume metadata")));if(null==e)return void ne().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,x.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,A.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),n=i(11944),s=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),n=i(11944),s=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),n=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),n=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let n=!1;function s(){n&&(n=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return n},t.pause=function(e=!0){!1===e?s():n||(n=!0,(0,r.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),n=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),n.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,w());return t=(0,a.clamp)(1,n,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),n=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),n=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),n=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),n=i(11944),s=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,s.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:n}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,n))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,n.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:n,lazyLoad:s,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(n=(n??[]).filter(u.gt0)).length&&n.push(320);const d=Math.min(...n),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const b=s&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=n.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),n=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),n=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),n=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),n=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),n=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),n=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),n=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,n.isFunction)(e)&&(0,n.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),n=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),n=i(38625),s=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),n=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,o=await i;if(!(0,n.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),n=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),n=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=n.length;(0,r.filterInPlace)(n,(t=>e(i,t))),t=t||s!==n.length,0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),n=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,n){return!(null==n||!l(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,n.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function T(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return T(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=T,t.toFixed=function(e,t){try{return M(e,(e=>T(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return h(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-T(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?T(e/r)*r:T(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,b(t)?T(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=b(...i.map((t=>t[e])));return n}function S(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&n(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,a]=(0,c.splitFirst)(i,"."),o=S(t,n);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),n=i(23175),s=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),n=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),n=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),a=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?o.indexOf(r)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),n=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,a=new Set(r??[]);if(t===e&&0===n&&0===a.size&&1===i)return[e];const o=n-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),n=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,n.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),n=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=b(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),n=i(61570),s=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{r&&(0,n.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,n=!0){const s=await o(e,i,n);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const n=i-Date.now();return n<=0?t.Timeout:o(e,n,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return l(e,n,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:n=!0}){const a=await o(e,i,n);return a===t.Timeout?(0,s.tot)(r):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),n=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),n=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),a=d[r];return(0,s.sigFigs)(e/n,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),a=h[r];return(0,s.sigFigs)(e/n,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),n=i(82798);t.ua=(0,r.lazy)((()=>(0,n.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,n)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),n=i(75556);function s(e){const t=e;return(0,n.isNumber)(e)?e:(0,n.isNumber)(t.id)?t.id:(0,n.isNumber)(t.assetId)?t.assetId:(0,n.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,r.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),n=i(39938),s=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),n=i(11448),s=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),n=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),n=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},49374:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),T=i(43414),_=i(82041),E=i(46573),D=i(53719),x=i(59387),k=i(39938),C=i(38625),F=i(88491),I=i(6314),O=i(61570),A=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=T.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",n)?.rootDir.nativePath,i=!0===a(this,r,"f",n)?.isReadySync(),s=!0===a(this,r,"f",n)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!s?a(this,r,"f",n):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",n)),o(this,r,(0,k.blank)(e)||!(0,_._libraryHasSettings)(e)?void 0:new r(e),"f",n))}static get priorInstance(){return a(this,r,"f",n)}static endPriorInstance(){const e=a(this,r,"f",n);return o(this,r,void 0,"f",n),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,s.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,_.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=T.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;T.Settings.maxConcurrentImports.hasValue()||(T.Settings.maxConcurrentImports.tmpValue=e,(0,x.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,O.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>A.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,s,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,s=new WeakMap,n={value:void 0}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),n=i(20902),s=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,s.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=s(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),b=i(91641),S=i(95557),P=i(4691),M=i(52289),T=i(10408),_=i(27519),E=i(49379),D=i(17875),x=i(79015),k=i(12737),C=i(49857),F=i(7157),I=i(85352),O=i(9483),A=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(_.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(_.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,x.ee)().on("fatal",$),(0,x.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,T.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Z))))}function Z(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,A.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=Z,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[O.LogLevels.fatal,"fatal"],[O.LogLevels.error,"error"],[O.LogLevels.warn,"warning"],[O.LogLevels.info,"info"],[O.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),b=i(7162),S=i(33148),P=i(55568),M=i(25516),T=i(38307),_=i(42041),E=i(95557),D=i(4691),x=i(2126),k=i(7383),C=i(70259),F=i(24905),I=i(44731),O=i(20902),A=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Y=i(39938),Z=i(88491),X=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{k.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,x.exit)({reason:"exit() event",status:0})))}));class ne extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,new Q.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,n,(0,b.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,s,"f").promise}get isReady(){return m(this,s,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=ne,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Y.mapNotBlank)((0,O.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Y.mapNotBlank)((0,O.getEnv)("PS_CRASH_"+this.name),(e=>{(0,X.later)((()=>{throw new B.WrappedError(e)}),5*Z.secondMs)})),(0,S.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,s,"f").reject():m(this,s,"f").resolve()}catch(e){console.error((0,A.errorToS)(e)),m(this,s,"f").reject((0,te.toErr)(e)),(0,x.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,A.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,x.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,x.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,x.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,x.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,x.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,T.stdoutWrite)({version:_.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,X.later)((()=>(0,x.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,T.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,T.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,n,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,n,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),n=i(7162),s=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,n.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:s.AssetVersion,AssetFileVersion:s.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),n=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(n.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+n),n):n}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),n=i(85297),s=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,o()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),n=i(92507),s=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,n.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,s.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function T(e){return(0,s.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function _(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),T);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=T,t.dateTag=_,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:_(r.date)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),n=i(43414),s=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...n.Settings.rootTagKeywordsAliases.values,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,s.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...n.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...n.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,s.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,s.tagDiff)(t,e),r=(0,s.tagDiff)(e,t),a=n.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,s.tagRefToS)(e[0]).toLowerCase());return t&&!(0,s.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},18130:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),T=i(79403),_=i(43414),E=i(88491),D=i(75556),x=i(61570),k=i(23175),C=i(6628),F=i(72537),I=i(51603);class O extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,n.set(this,0),s.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),_.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||_.Settings.dbForceRecover.valueOrDefault)&&(T.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),n=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:n,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,x.pick)(this,"schema","dbFile")}get open(){return null!=l(this,s,"f")&&l(this,s,"f").open}get inTransaction(){return this.open&&!0===l(this,s,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,s,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,s,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===_.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(_.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,n,(e=l(this,n,"f"),++e),"f")%_.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,s,"f")?.pragma("incremental_vacuum"),l(this,s,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,k.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,s,"f")?.open&&(this.logger.info("closing db",l(this,s,"f")),l(this,s,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,s,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),n=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,n),i||await(0,y.dbBackupCold_)(n,e),e.join(this.dbFile.base)}}t.Db=O,n=new WeakMap,s=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),T=i(19067),_=i(41593),E=i(94332),D=i(91894),x=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class k extends h.EndableInterval{static for(e){return new k(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",s).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,x),n.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,n,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,_.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,n,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,n,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,T.fmtDuration)(Date.now()-l(this,n,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=k,n=new WeakMap,r=new WeakSet,s=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:x,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),n=i(7162),s=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),T=i(91894),_=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function x(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return k((0,l.pathToDb)(t,"models"))}function k(e){return e.sibling("db-info.json")}async function C(e=x(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw _().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,T.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=x,t.libraryDbInfoFromDbFile=k,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let n,o;await i.tryAcquire_();const u=k(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(n=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==n||null==o){const i=await(0,s.getLiveDbDir_)(e),r=await i.db.uri_();n=i.useReplica,n&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>_().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:n})}})),null==o||null==n)return _().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();n&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!n),(0,T.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw _().error("Failed to set up model db",{error:e}),(0,T.addDbSetupError)(e),i.release(),e}return _().tap({msg:"dbModelSetup()",result:{db:o,useReplica:n,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),n=i(4866),s=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,n.lazy)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:n}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const s=n[i].bind(n);return null==r.bindings?s():s(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),n=i(39938),s=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,s.isError)(e)||!(0,n.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),n=i(7162),s=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,n.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),n=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),s=r[0],l=r.slice(1),u=s?.id;if((0,o.isEmpty)(n)||(0,o.isEmpty)(l)||null==s||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:s,winnerId:u,leafs:n,losers:l});const d=(0,a.splitTagPath)(s._path).slice(0,-1),f=[...d,n[0]];s._path=(0,a.joinTagPath)(f),s.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??s.parentId,h().info("mergeTags()",{winner:s,losers:l,winnerTagPath:f,leafs:n});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:s.parentId,path:s._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:s._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:s,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,s.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,s.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const n=r(i(40514)),s=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,s.lazy)((()=>(0,n.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),T=i(39938),_=i(88491),E=i(43947),D=i(87748),x=i(66776),k=i(8199),C=i(47025),F=i(91894),I=i(12586),O=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,k.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*_.minuteMs},(()=>a(this,r,"m",n).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),n=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(n);return o?await n.bind(I.Migrations)(this.db):await a(this,r,"m",s).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,n=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(_.secondMs,3*_.secondMs)),await(0,x.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),_.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},s=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,T.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,O.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),n=i(4866),s=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),T=i(82798),_=i(54578),E=i(85476),D=(0,n.lazy)((()=>(0,s.mkLogger)("db.Migrations"))),x=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function k(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>x.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=k,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},k),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const n of t){const t=(0,T.toS)(n.ids).split(","),s=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(s,(e=>[e.shown,e.version,e.updatedAt])),o=s.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:_.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),n=i(4866),s=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),T=i(24603),_=i(87748),E=i(6314),D=i(75556),x=i(26588),k=i(44726),C=i(17078),F=i(39784),I=i(82798),O=i(9069),A=i(70582),L=(0,n.lazy)((()=>(0,s.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,k.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,T.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,_.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,A.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const n=await(0,y.sqliteNativePath_)(),s=await(0,r.thenElapsed)((0,a.stdout_)(n,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+s.elapsedMs+"ms",s.result),s.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,O.modelDb)()?.end()),await(0,A.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const n="wal_checkpoint("+r+")",[s]=(0,F.toA)(t.pragma(n));return L().info("checkpoint()",{pragma:n,result:s}),(0,D.gt0)(s?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):s};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),n=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),s=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},n),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:n});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:n});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),s.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,x.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,x.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),n=i(1058),s=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,s.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,s.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,n.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),n=i(89253);function s(e){const t=new n.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=s,t.localTableInfo=function(e){return s(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),n=i(43414),s=i(82798);t.withDbSync=function(e,t,i=n.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,s.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=n.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,s.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},32159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(97742),n=i(7162),s=i(37980),a=i(37445),o=i(10408),l=i(98250),u=i(72461),c=i(3874),d=i(11944),h=i(39938),f=i(38625),m=i(87748),p=i(61570),g=i(7127),y=i(49374),v=i(20990),w=i(92045),b=i(18273),S=i(66056),P=i(30690),M=i(50725),T=i(66953),_=i(63216);!async function(){try{const e=new s.CLI(g.ServiceNames.list).add(w.LogArgs,a.WriteSettingsArg);e.add({beforeParse:e=>e.option("--reindex","Rebuild the fulltext search indexes before running any query.").option("--query ","Apply the given query and return all matching asset file paths. Must be the last argument. Incompatible with --where.").option("-j, --json",'Emit a JSON object for every asset file with "hidden" and "shown" flags').option("--dump","Emit a JSON object that includes all column values").option("--where ","Apply a SQL WHERE clause to filter the rows returned.").option("--orderby ","Apply a SQL ORDER BY clause to filter the rows returned.").option("--looks-like ","Find images that look like the photo or video specified by FILE. Use a full pathname.").option("--tags","List all tag paths along with their counts.")});const t=(await e.parse()).opts(),i=(0,d.mapNotEmpty)(t.query,(e=>e.join(" "))),r=(0,f.isTrue)(t.dump),o=r||(0,f.isTrue)(t.json),E=t.where;if(null!=i&&(0,h.notBlank)(E))throw new Error("--query cannot be used with --where");const D=t.order,x=new v.Service({name:"list"});await x.ready;const k=await y.Library.instanceRequired().modelDb();(0,f.isTrue)(t.reindex)&&await(0,_.forceRunTagMaintenance)();const C=(0,n.mkLogger)("list");if((0,f.isTrue)(t.tags)){const e=M.Tag.ops().allf((e=>M.Tag.orderBy(e)));return void console.log((0,m.stringify)(e.map((e=>(0,p.pick)(e,"path","assetCount")))))}let F=P.Asset.query().join("AssetFile","AssetFile.assetId","Asset.id").join("AssetTag","AssetTag.assetId","Asset.id");if(F=F.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",shownFile:"AssetFile.shown",mountpoint:"AssetFile.mountpoint",uri:"AssetFile.uri",hidden:"Asset.hidden",rating:"Asset.rating"}).distinct(),(0,h.notBlank)(t.looksLike)){const e=l.PosixFile.for(t.looksLike);C.info("Calculating image hash for "+e);const i=await e.sha(),r=await(0,u.imageHash)(e);if(null==r)throw new Error("Failed to generate image hash for "+e);C.info("Looking for assets with matching meanHash or SHA",{meanHash:r.meanHash,SHA:i}),F=F.where((e=>e.where("AssetFile.meanHash",r.meanHash).orWhere("AssetFile.sha",i)))}r&&(F=F.select((0,b.knex)().raw("AssetFile.*"),(0,b.knex)().raw("Asset.*"))),F=(0,h.notBlank)(E)?F.andWhere((0,b.knex)().raw(E)):P.Asset.shownUnhidden(F);const I=(0,h.notBlank)(D)?D:"uri",O=null!=i?(0,T.queryStringToSql_)(i,F).orderByRaw(I):F,A=(0,S.toSqlQuery)(O);C.info("Running SQL query...",{sq:A});const L=Date.now(),R=k.prepare(A.sql).iterate(A.bindings);C.info("query took "+(Date.now()-L)+"ms");for(const e of R){const t=await(0,c.uri2nativePath)(e.uri,e.mountpoint);o?console.log((0,m.stringify)({path:t,...(0,p.omit)(e,"id")})):console.log(t??e.uri)}}catch(e){console.log("Failed: "+(0,o.errorToS)(e)),(0,r.exit)(1)}finally{(0,r.exit)(0)}}()},30690:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),T=i(38625),_=i(9381),E=i(87748),D=i(66776),x=i(75556),k=i(26588),C=i(39784),F=i(49374),I=i(18290),O=i(89452),A=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),n=await(i?.mtimeMs());null!=i&&null!=r&&null!=n&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:n,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?n.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,x.gt0)(e)?n.ops().firstf((t=>n.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??n.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return n.ops().count(n.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),s=n.ops().findById(e);if(null==s)return void r.warn("asset not found");const a=s.isActive(),o=s.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=O.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),n.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await n.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,n,"m",s).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,n,"m",s).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,n,"m",s).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=n.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),n.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,A.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const n=new O.AssetFile;return this.addAssetFile(n),!0!==t?.skipUpsert?await n.upsertIfNeeded_(e):await n.setFile_(e),n}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=n.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const n=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(n,1),n}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=n.dbl.all(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const n=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==n.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:n});const s=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=s){this.capturedAtLocal=s.capturedAtLocal,this.rating=s.rating,this.durationMs=s.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,k.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const n=!0;this.imgAttrs.set(t,await r.imgAttrs(t,n,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,_.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,k.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,n=W,r=new WeakSet,s=function(){return n.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=n.dbl.first(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=n.dbl.first(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),T=i(31053),_=i(43414),E=i(65642),D=i(27446),x=i(3874),k=i(19209),C=i(25116),F=i(36974),I=i(22356),O=i(11944),A=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),Z=i(13222),X=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>k.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Z.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=s(this,r,"m",n).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return _.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=_.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,q.assignAllFields)(this,(0,q.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=s(e,r,"m",n).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,T.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),n=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>n.push(e))),this.isVideo)return n;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return n;const s=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,T.previewToDownloadable)(i.base,e)))));return n.push(...(0,O.uniqBy)(s,(e=>e.size))),n}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=k.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=k.URI.parse(this.uri),n=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:n};function s(){return(0,A.at)((0,A.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(s(),(0,A.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&s()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=k.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:s(),thisVolSha:t}),s()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:s()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:n}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,n=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?_.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),n=i(75556);t.toAssetId=function(e){const t=(0,n.toGt0)(e?.assetId)??(0,n.toGt0)(e?.id);if(null==e||null==t||!(0,n.isNumber)(e?.capturedAtLocal))return;const i=((0,n.toGt0)(e.v)??(0,n.toGt0)(e.updateCount)??(0,n.toGt0)(e.updatedAt)??0)%1e6,s={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,n.gt0)(e.durationMs)&&(s.durationHMS=(0,r.durationHMS)(e.durationMs)),s}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),n=i(2934),s=i(7907);class a extends s.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,n.parseJSON)(this._priorValueJson)}get newValue(){return(0,n.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class n extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=n,n.$tableName="AssetTag",n.$uniqueColumnName="assetId,tagId",n.$useCache=!1,n.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),n=i(7162),s=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,n.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,s.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),n=i(7383),s=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,n.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,n.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{s.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const n=i(47261),s=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,s.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[n.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const n=this.class(),s=(0,l.notEmptyOr)(r,n.ops().columnNames());return(0,h.fromEntries)(s.map((t=>this._get(t,e,i))),t?{$ctor:n.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,s.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),n=i(82341),s=i(4866),a=i(66776);t.modelDb=(0,s.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,n.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),n=i(11944),s=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[s,o]of Object.entries(t)){if("$ctor"===s)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(s,i);e[t]=null==o?o:(0,n.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,s.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,n.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,n){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${n}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:n,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),T=i(39938),_=i(24603),E=i(1429),D=i(87748),x=i(66776),k=i(75556),C=i(61570),F=i(39784),I=i(78650),O=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,n.set(this,void 0),s.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,n,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,O.addModelClass)(e),d(this,s,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,s,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,k.gt0)(e)&&h(this,s,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,x.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(k.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,k.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,n,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),s=this.dbl.runf((e=>e.insert(i)));return t.id=(0,k.toInt)(s.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,x.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,T.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,T.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),n=this.findOneBy(t);return h(this,r,"m",l).call(this,i,n),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,n,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),n=[];for(const s of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(s.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,_.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),n.push(e)}}return n}delete(e){const t=(0,F.toA)(e).filter(k.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,s,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const n={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(n);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),n=i(4866),s=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,n.lazy)((()=>(0,s.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const n=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=n)return void c().debug("applyOnce(): already done",{priorCompleted:n});const s=this.ops().insertOne(e),o=await t(s);return(0,r.ending)()||s.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),n=i(97742),s=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),T=(0,s.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,s.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const _=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),D.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return T().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return T().tap({msg:"times()",result:this.dbl.all({sql:_,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?T().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:n.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),n=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class s extends n.TimestampedModel{}t.ProgressMeta=s,s.$tableName="ProgressMeta",s.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),n=i(7162),s=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,n.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,s.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),T=i(26588),_=i(44726),E=i(39784),D=i(17078),x=i(52465),k=i(18273),C=i(66056),F=i(54578),I=i(30690),O=i(14405),A=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,_.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,k.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,_.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=s(this,r,"m",n).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,n=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:n});try{if(null==n)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,k.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=n._path,this.logger().info("changePath(): replacing with sibling",e),A.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:n.id}))),A.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...n.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:n.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,T.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,_.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(O.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,_.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,n]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(O.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(O.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,n=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(x.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),n=i(59553),s=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,n.tag_fts_root)(e._path),path:(0,n.tag_fts_path)(e._path)})));(0,s.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const n=c.$tableName;this.dbl.runScript([`INSERT INTO ${n}(${n}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),n=i(7162),s=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,n.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=s.Settings.minStreamCorrPct.valueOrDefault/100,i=[],n=e.filter((e=>e.length>5));for(const e of n){const n=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==n?i.push(e):n.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),n=i(11944),s=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(s.gt0);return(0,n.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,s.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},77837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(23595),n=(0,i(4866).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return n().parse(e)}},26825:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(44726),o=i(82798);function l(e){return"object"==typeof e&&(0,n.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,s.isTrue)(e?.not)?(0,s.isFalse)(e?.term):(0,s.isTrue)(e?.term)},t.SetQuerySymbols={not:"ยฌ",and:"โˆง",or:"โˆจ"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,s.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},40234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(13779),n=i(11254),s=i(11944),a=i(59694),o=i(39938),l=i(38625),u=i(84253),c=i(82798),d=i(77837),h=i(26825);function f(e){return(0,a.sortBy)((0,s.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[ยฌ(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[n,s]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(s,(e=>e.type===t.type));for(const e of a)n.push(...e.queries);const l={type:t.type,queries:f([...n,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:n.TagRoots.Keywords,keyword:n.TagRoots.Keywords,keywords:n.TagRoots.Keywords,dir:n.TagRoots.fs,directory:n.TagRoots.fs,folder:n.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},4728:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const n=r(i(50764)),s=i(4866),a=i(7162),o=i(19658),l=i(53525),u=i(75556),c=r(i(12436)),d=(0,s.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new n.default.Parser(n.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!o.isProd&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},66953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(4866),n=i(7162),s=i(85590),a=i(68074),o=i(6667),l=i(43414),u=i(61473),c=i(39938),d=i(38625),h=i(87748),f=i(82798),m=i(18273),p=i(30690),g=i(77837),y=i(26825),v=i(40234),w=i(4728),b=(0,r.lazy)((()=>(0,n.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const n="Asset.updatedAt"===r?s.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=n(l),c=l?.following()?.toDateTime(),d=n(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",M(t));case v.AssetTermNs.excluded:return _({qb:e,column:"Asset.excludedAt",whereNull:0===M(t)});case v.AssetTermNs.deleted:return _({qb:e,column:"Asset.deletedAt",whereNull:0===M(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),n="="===t.op,s=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const n=i[r];return i[r]=t.get(n)??n,i.join("/")}(t,i);if(r||n)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+s.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(n?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+T(s.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+T(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function M(e){return P(e)?1:0}function T(e){return e.includes("*")?e.split("*").map(T).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function _({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},12436:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function n(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const s=r(i(34235)),a=i(11944),o=i(82798);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=s.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-ยฌ]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|โˆจ|\|{1,2}) +/,and:/(?:and|AND|And|โˆง|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:n},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:n},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:n},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:n},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:n},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:n},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),n=i(55568),s=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,n.isStatsDbMigrator)()&&(await t.migrate_(),new s.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},97840:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),T=i(39784),_=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(_.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,T.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",n).call(this,e);return null!=t&&(await l(this,r,"m",s).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),n=await e.posixFile_();null==n&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(n);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",s).call(this,n,e),h=null!=await l(this,r,"m",o).call(this,n,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:n.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(n);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===n.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+n.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,n=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),n=await this.findLibraryFileWithSameContents(e,r);if(null!=n)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:n}),n;const s=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:s,dest:r}),e.copyFile_(s)},s=async function(e,t){const i=await e.existingSidecars(),n=[];for(const e of i)n.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(n)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),n=i(7383),s=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,s.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,n.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,n.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const n=r(i(49411)),s=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),T=i(19067),_=i(75556),E=i(8199),D=i(44726),x=i(11254),k=i(89452),C=i(50725),F=i(21250),I=i(54578),O=(0,s.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,s.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return O().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const A=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:A,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),n=O().addContext(".runTagMaintenance()");n.info("starting",{ctx:i});try{n.info("validating all tags..."),C.Tag.validate_(),n.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(n.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),n.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),n.info("vacuuming orphan tags..."),await L()}catch(e){O().warn("runTagMaintenance() failed",e)}const s=Date.now()-r,a=(0,_.clamp)(A,15*P.minuteMs,20*s);t.runTagMaintenance.setMinCallDelayMs(a),O().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:s})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([x.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(x.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===x.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,T.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:n.default.sep,suffix:n.default.sep}),n.default.sep):k.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},34235:e=>{"use strict";e.exports=require("moo")},50764:e=>{"use strict";e.exports=require("nearley")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=32159);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(74485),{decode:s}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=s(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),n=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),n=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:n}=i(74485),s=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,n,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:a?.length?a:void 0,version:e,purpose:l}:n}const u=o(n);return s(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),s=a(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},45112:(e,t,i)=>{const r=i(6113),n=i(16464),s=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=s(n,o,p,t),v=m(y,f);return a(n,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=s("v1.local.",r,a,t),v=m(g,p);if(!l(n,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=s(o,l,w,t,n),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=s("v3.local.",n,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:n}=i(35740);n||(n=e=>null!=e&&e instanceof r),e.exports=n},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const n=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(n*t);case"day":case"days":case"d":return Math.round(864e5*n);case"week":case"weeks":case"w":return Math.round(6048e5*n);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*n)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:n}=i(39084),s=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),n=i(97540),s=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=n(u,e,t,i,l),d=await r(a,c,o);return s(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),n=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:n}=i(45112),s=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=s(c,e,f,h,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),n=i(37794),s=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:n,V2:s,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v1.local"),{pre:s,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v1.local"),s=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=s(e,o);t=n(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),n=i(76331),s=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:n,encrypt:s,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),a=n(r.generateKeyPair),o=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:n})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=s(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),n=i(49172),{generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),n=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=n.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=n(e,a);t=o(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:n}=i(42421),{post:s}=i(97362),a=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v3.local"),s=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=n(t);const f=s(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v3.local"),s=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),n=i(58271),s=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:n,encrypt:s,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),a=i(45445),o=i(70067),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),n=i(25054),s=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=s(e,h),m=n(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),n=i(42417),s=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),n=i(5816),{generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:o,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=n(e,u),d=s(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),n=i(80094),{_checkPublicKey:s}=i(80244),{post:a}=i(97362),o=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await n("v4.public.",e,void 0,64,t,c);return a("v4",s,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),n=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(n.isProd?"":`-${n.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),n=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return _(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return _(e,t,((e,t)=>(0,h.gt)(e,t)))}function T(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function _(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function x(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=T,t.least=function(e){return T(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const n=[];for(const s of D((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of D((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await x(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const n=r(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),T=i(43414),_=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,_.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:n.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:T.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,_.commandTimeoutMs)(),minDelayBetweenSpawnMillis:T.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:T.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class n{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=n},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>n){const e=this.getFirst(s);null!=e&&(r=e,n=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let n=!(0,r.noColor)();function s(e,t){return i=>n?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){n=e??!(0,r.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),n=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),n=i(9678),s=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),n=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),n=i(4866),s=i(98250);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),n=i(40786),s=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),n=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),n=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){n(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),n=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),n=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?T():_()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function T(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function _(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=T,t.localePosix=_,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),n=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(n.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),n=i(74269),s=i(78109);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),n=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),n=i(51498);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),n=i(75556),s=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,n.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const n=r(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&n.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=n.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),n=(0,o.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),n=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,n]of(0,u.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,u.keys)(e))if(r[s]=t(s,e[s]),n++,(0,l.gt)(n,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),n=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function T(){return"fedora"===(0,t.osDistributionLinux)()}function _(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,n.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=T,t.isAlpine=_;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return x(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":x(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(T())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(_())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),n=i(39784),s=i(21142);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const n=i(5712),s=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),T=i(46852),_=i(46027),E=i(4586),D=i(17875),x=i(98462),k=i(25015),C=i(3955),F=i(51053),I=i(71663),O=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),A=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))O().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,l.isEmpty)(n))return O().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(n);if(null!=o){for(const n of r){const r=await n.readJson();if(null==r){O().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){O().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){O().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(O().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),s.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,n.pidExists)(r)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),n=t.getTime(),s={...e,cmd:r,startTime:n};return await i.writeJson_(s),O().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void O().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,T.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{O().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(x.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,_.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),n=i(7162),s=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const n=r(i(97742)),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),b=i(46852),S=i(69317),P=i(9288),M=i(51053),T=i(71663),_=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return _().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function x(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(T.PowerShell.instance().ended)return L();const e=await T.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?L():x(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],O))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[n.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),n.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return L(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>x(e)))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),n.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===n.default.pid))||r.push({pid:n.default.pid,start:new Date(v.StartTs),cmd:"node "+n.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),n=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),n=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...n)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=n,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new a.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return n.promise}(...n)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),n=i(82798);function s(e){return e instanceof a?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(70612)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>_.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let T=!0;const _=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||_().has(e))return;_().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),T)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;T=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),n=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,n.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const n=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return n.setShim=e=>{i=e},n.hasShim=()=>null!=i,n}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),n=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,n.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),n=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),n},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),n=this.valueOf(this.store[r]);if(e===n)return{found:!0,index:r};e>n?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),n=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),n=i(18991);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(n+"\n"),(0,o.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+n+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function T(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=T;const _=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=_.exec(T(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function x(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,a),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(s,(()=>n.push(i)))})),n}function S(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const T=/[^\da-z]+/gi;function _(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(T,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,n-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=_,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:_(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),n=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,n,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,r,"m",n).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),n=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,n.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(70612)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[s]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const n=t();return null!=n&&this.set(e,n),n}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",n).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const n=i.deref();null==n?a(e,r,"f").delete(t):yield n}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const n=i.deref();null==n?a(e,r,"f").delete(t):yield[t,n]}}()}[(r=new WeakMap,i=new WeakSet,s=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,n=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),n=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),n=i(66776),s=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,n,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...n,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,n.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>T(e*t)))}function T(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function _(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=T,t.mtime2sort=_;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,n.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function x(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const n=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:_(n),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,n.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=x(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=x,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(92332)),s=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),T=i(61570),_=i(26588),E=i(46234),D=i(21669),x=i(7162),k=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,x.mkLogger)("async.Deferred")));class O{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new n(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,T.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,_.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,_.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=O,n=O,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],n.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}},r=new WeakMap,n=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=r.isTest?e:e||n}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,n.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,s,0,"f"),h(this,n,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,n,"f")?void 0:Date.now()-d(this,n,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,n,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),n=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let n,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:n):(s=!0,n=(0,r.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>n,o.force=async()=>(await n,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),n=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function T({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(n)?(0,d.thenOrTimeoutError)(i(a),n):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((n=Math.round(n??(0,w.maxCpus)()))<=1)return T({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=n?b.PermissivePromises:new b.Promises(i,(()=>n))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(n);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=T,t.mapAsyncSerial=async function(e){return(await T(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const a=await i(n,s);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function T(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return T(e,Date.now()-i),r},t.pushTime=T,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,n,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),n=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,n.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),n=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,s.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],T=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],_=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:T),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(n.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:x({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function x({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,o.compactValues)({...(0,t.sanitizedEnv)(),..._(),...i?(0,f.childProcLocale)():{},...E(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(n);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(n),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return n}t.childEnv=x},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(17718)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),T=i(46027),_=i(49379),E=i(79141),D=i(83837),x=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function O(e,i,r,n=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,T.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&o.push((0,T.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),o.push((0,T.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function A(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,x.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),O(n.default.execFile(e,t,s),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=A(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||n?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const T=y.join("");(0,l.notBlank)(T)&&v.push(new Error(T)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const x=i.isIgnorableError??_.isIgnorableError,k=v.filter((e=>!0!==x(e)));if(k.length>0)throw 1===k.length?k[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:T}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),O(n.default.spawn(e,t,s),e,t,i)},t.execFile=A,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),n=i(43414),s=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),T=i(17875),_=i(79141),E=i(45512),D=i(7162),x=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new _.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,n,"f")||a||(this.lastError=s,(0,T.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,x.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,T.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,T.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const n=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=n?a.join("$library",i.posixPathFrom(n)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),n=i(97742),s=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,n.exit)(0)})),e.parse(n.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),n=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,n.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),n=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(97742)),s=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(n.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),n=i(11944),s=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),n=i(82041),s=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),n=i(11944),s=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,n.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),s=b(r);return null!=r&&null!=s&&((0,n.pushUniq)(s.closeLabhashes,e),(0,n.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(r))),s})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),n=i(11944),s=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(_(T(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,n.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let n=0;ne>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function T(e){const[t,i,r]=v(e),n=(t+16)/116,s=i/500+n,a=n-r/200,o=s*s*s,l=a*a*a,u=o>S?o:(116*s-16)/P,c=t>8?Math.pow(n,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function _(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=T,t.xyz2rgb=_,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function x(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,r]=(0,f.clampRGB)(e),n=Math.max(t,i,r),s=n-Math.min(t,i,r),a=s?n===t?(i-r)/s:n===i?2+(r-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),n?s/n*100:0,n/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,r]=e,n=(200-i)*r/100;return[t,n>0&&n<200?i*r/100/(n<=100?n:200-n)*100:0,n/2]}function I(e){const[t,i,r]=e,n=i*(r<50?r:100-r)/100;return[t,n>0?2*n/(r+n)*100:0,r+n]}function O(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,n=Math.floor(t),s=r*(1-i),a=r*(1-(t-n)*i),o=r*(1-(1-t+n)*i),l=n%6;return(0,f.clampRGB)([255*[r,a,s,s,o,r][l],255*[o,r,r,a,s,s][l],255*[s,s,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(D,e,(()=>x(e,t))):x(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return O(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=O,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),n=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,s]=e,[a,o,l]=t,u=i-a,c=r-o,d=s-l,h=(0,n.sqrt)(r**2+s**2),f=h-(0,n.sqrt)(o**2+l**2),m=(0,n.sqrt)(c**2+d**2-f**2);return(0,n.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,n.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,n.sqrt)(d**2+h**2))/2,m=.5*(1-(0,n.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,n.sqrt)(p*p+l*l),v=(0,n.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const T=2*(0,n.sqrt)(y*v)*Math.sin(M/2),_=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+b:(D=(w+b)/2,D-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const x=(_-50)**2,k=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*x/(0,n.sqrt)(20+x),F=1+.045*E,I=1+.015*E*k,O=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),A=2*(0,n.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*O)*A;return(0,n.sqrt)(Math.pow(S/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(T/(o*I),2)+L*P/(a*F)*T/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),n=i(75556),s=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,n.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,n.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,n.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,n.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,n.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,n.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=T[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function x(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,n.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{..._,seed:e}),n=k(r.centroids,f.length);if(n.lengtht&&x(g-1);const s=n.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const n=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,n)));null!=s&&(0,l.times)(r,(()=>t.push(s.value)))}return t.p84}(s);return{...r,centroids:s,description:{kIn:g,kOut:r.centroids.length,kMerged:n.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),O=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(O),pixelCount:f.length}),{dominantColors:O,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],T={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},_=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:T[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const n=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(n))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=n));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:n,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:n,minK:t,retries:r,pixelCount:e.length,filteredCount:s.length}),E({labs:e,minK:t,thresh:.75*n,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;x(e);const s=e.size,a=(0,n.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:s,pixelCount:i,pctOmitted:l})}}function x(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,n]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:r}):(e.delete(r),e.incr(a.labhash,n))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const n=t/100;return(0,s.sortBy)(r.filter((e=>e.size>n)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{_.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=x,t.mergeNearCentroids=k},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),n=i(75556),s=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,n.within)(0,100,e[0])&&(0,n.within)(-110,110,e[1])&&(0,n.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const n=(i.stdDev??0)+(r.stdDev??0),s=n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),n=i(61570),s=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,n.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,n.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),n=i(65113),s=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,n.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),n=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),n=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function T(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function _(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),x(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function x(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=_(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,a.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=T,t.toDated=function(e){return T(e)?e:void 0},t.mapDated=function(e,t){return T(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=_,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=x,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),x)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=x(e)),r??(r=x(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),n=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),n=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),n=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:n,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),n=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),n=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),T=i(64455),_=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return n.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function x(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(n=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),a=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${E(s)}:${E(a)}`},t.toExifDateTime=x,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):x(e,(0,_.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function O(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?n.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,_.hasZone)(t)?C:k):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(O(e,t),l.dayMs)},t.diffMillis=O,t.closeTo=function(e,t,i){return(0,u.mapOr)(O(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(r+1),l=(0,_.getZoneName)(e),u=l===(0,_.getZoneName)(t)?l:void 0,c=n.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,_.hasZone)(e)},n=(0,M.normalizeZone)(t);if(null!=e&&null!=n&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(n,r):x(e)?.setZone(n,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,_.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),T=i(55170),_=i(45161),E=i(50140),D=i(82701),x=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:A.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return A.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return A.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=O({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,T.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,T.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function O({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,T.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:T.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of A.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=O;class A{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",s).call(this))),a(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;_.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=O({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=A,r=new WeakSet,n=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,x.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},A.instance=(0,u.lazy)((()=>new A));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return _.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,x.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),n=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(a(e))||(0,n.gt0)(o(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),n=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),n=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?T(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(T(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return T(Date.now()-e,t)}function T(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),n=i(59694),s=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,n.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),n=i(4866),s=i(92507),a=i(43414);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const T=/\b(?Z|UTC|GMT)\b/,_=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,x=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),T,new m.RegExpEscaped("|"),_,D,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,O=(0,s.lazy)((()=>(0,m.concatRegexp)([I,_,x,m.RegExpOptional.from(k)])));function A(e){return F(O().exec(e))}t.ianaZoneToOffsetMinutes=A,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=A(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),T=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=x(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function x(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof n.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=n.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return _().includes((0,v.datedToMillis)(e))?"bad date (via millis)":T().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=x,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function O(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function A(e,t,i){return(0,u.gt0)(i)&&n.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||O(t,e))&&(!(0,u.gt0)(i)||A(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=O,t.validDay=A,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),n=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),n=i(1629),s=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+s.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,n.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),n=i(82341),s=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,s.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,n.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),n=i(7162),s=i(61253),a=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,s.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),n=i(49379),s=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+s.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+s.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),n=i(85590),s=i(11944),a=i(61570);function o(e){return null===e||(0,s.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,n.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),n=i(19658),s=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(s.Settings.dbBatchSelectSize.valueOrDefault*(n.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),n=i(75556),s=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,n.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let n;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();n=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/s.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:n});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*s.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),n=i(75556),s=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,n.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,s.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),n=i(65886),s=i(76915);t.sqliteFiles=function(e){return[e,...n.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[s.SqliteExt,...[...n.SQLiteSuffixes,"-shm"].map((e=>s.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),n=i(75556),s=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,n.isNumber)(e))return e.toString();const t=(0,s.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,s.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let n;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),n=i(24603),s=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,s.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,n.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,s.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,n.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),n=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),T=i(58676),_=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function k(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,_.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,_.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),n=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),n=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),n=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),n=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),n=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),n=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),n=i(82798),s=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,n.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),n=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function T(e){return y(M(e))}async function _(e){return y((0,n.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await T(t),await _(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=T,t.setupLibraryDbDir_=_},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),n=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!n.isProd&&!(0,s.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),n=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(87561)),s=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(n.default.readFileSync(r)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(s))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),n=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const a of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const a=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),n=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(S(e)),r=t?.maxLen??400,n=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,n)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),n=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),n=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),n=i(88491),s=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),b=i(6231),S=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class T{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=T,T.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new T(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),n=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,n.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class n extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=n},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),n=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),n=i(87489);function s(e,...t){return n.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,r.lazy)((()=>s("exit")))},80313:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),n.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,r,"f").get(e);return null!=a&&(a.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),n=i(4866),s=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,n.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let n=!1;t.isSyncing=function(){return n},t.setIsSyncing=function(e){n!==e&&(n=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),n=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,n.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,n.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),T=i(38625),_=i(88491),E=i(43383),D=i(24603),x=i(16475),k=i(1429),C=i(87748),F=i(21040),I=i(66776),O=i(75556),A=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),ne=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,O.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,O.isNumber)(e.pid)&&(0,T.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=_.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),n=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=n,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),_.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let n=!1;if((0,P.isEmpty)(i))return;const s=be((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),n||(n=p(this,r,"m",f).call(this,e));n&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,O.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,A.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},n=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?n.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(n.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,n),this.save(),n)}}t.SharedState=Se,n=Se,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*_.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:_.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,s,"f"),b.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:n}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(n)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(n,n,"f",u)),ce.Settings.cacheDir.watchLater(p(n,n,"f",u)),ce.Settings.sharedStateDir.watchLater(p(n,n,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,ne.nativePathsEqlSync)(e,n.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(n.instance()),n.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,x.shortStack)());p(n,n,"f",l).call(n);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new n(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),n=i(79015);let s=!1;(0,r.later)((()=>(0,n.ee)().on("updateReadyToInstall",(()=>s=!0)))),t.isUpdateReadyToInstall=function(){return s}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(87561)),s=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const a=n??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),n=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),T=i(92585),_=i(39938),E=i(88491),D=i(24603),x=i(1429),k=i(87748),C=i(66776),F=i(75556),I=i(61570),O=i(98510),A=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),ne=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,_.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new Se(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(_.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,A.pad2)(t+1),(0,A.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,O.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,T.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*E.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),n=i(17310),s=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(n.ExtTypes.Video),t.isAssetFileExtension=o(n.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),n=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),n=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(49411)),s=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),n=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,n.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const n=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(n);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(n,(async(e,i)=>{g().trace("callback",{nativePath:n,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:n}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(n,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,n.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class T{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new T(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await o.stat(t);return new T(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return T.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new T(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>T.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new T(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=T},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),T=i(85943),_=i(82341),E=i(20902),D=i(9483),x=i(51053),k=i(38336),C=i(51776),F=i(43414),I=i(77390),O=i(98462),A=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:O.BaseFile.for(e),n=V.test(t)||r.isDirectorySync(),s=(0,R.native2posix)(r.nativePath),a=n?(0,m.ensureSuffix)(s,"/"):s;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",n).bind(this)):{}}}r=new WeakSet,n=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((x.isWin?"*":"")+"/"+t.s+"/",t.desc));if(x.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}x.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const n=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===n.length&&e.push(new U(`**/${t}/${n[0]}/`,r)),n.length>1&&e.push(new U(`**/${t}/(${n.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:ne,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[n,s]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:n,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return k.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function ne(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function se(e){return(0,S.thenNot)((0,A.isHidden)(e))}function ae(e){return!(0,T.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,_.libraryDirPosixFile)(),(0,_.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),n=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,n.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),n=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,n.pick)(await(0,r.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),n=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,n.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(a)?void 0:{ext:a,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),T=i(92332),_=i(11944),E=i(37609),D=i(88491),x=i(24603),k=i(19067),C=i(66776),F=i(75556),I=i(23175),O=i(20636),A=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),w(this,n,"f",s)+1),"f",s),(0,_.compactBlanks)([q.TokenRadix.encode(w(this,n,"f",s)),N.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return w(this,n,"f",o).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=w(t,n,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(n,n,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,_.filterInPlace)(w(n,n,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),n=i(44726),s=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),T=i(91641),_=i(17354),E=i(79015),D=i(3955),x=i(8177),k=i(43414),C=i(91464),F=i(37086),I=i(59873),O=i(95725),A=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,x.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,x.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,O.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:T.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),n.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,n,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,n,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,_.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,n,"f")});const e=c(this,n,"f"),i=await(0,A.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,n,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,n,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,O.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,n,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,n,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),n=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(87561)),s=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44470)),s=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(6005)),s=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),n=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),n=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),n=i(66776),s=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),n=i(44726),s=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),n=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,n.toNativePath_)(e),r=(0,n.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,n.toNativePath_)(e))===await(0,r.actualPath_)((0,n.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function T(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const r=await Promise.race([_(e,t),D(e,t)]);return t.halt(),r}(t.nativePath)))}async function _(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,T)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=T},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44470)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return _((0,y.posix2native)(e))},t.extname=function(e){return _(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function _(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function E(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(g.isLinux?r===n:(0,m.equalsIgnoreCase)(r,n))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=_,t.parentBasename=E,t.grandParentBasename=function(e){return E(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),F([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("โ€ฆ"),F([...n,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=_(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function T(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function _(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...T()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([..._(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,n,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),T=i(66776),_=i(75556),E=i(61570),D=i(20636),x=i(49049),k=i(17078),C=i(82798),F=i(13779),I=i(7162),O=i(14889),A=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),ne=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:O.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,A.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,A.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,T.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,T.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===x.PS_LIBRARY_SCHEME?1:t.scheme===x.PS_LOCAL_FILE_SCHEME?2:t.scheme===x.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,A.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,A.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,T.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:n,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*n,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,A.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,_.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,A.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,D.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:O.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(O.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,_.clamp)(O.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,T.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,A.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,_.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,T.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,T.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),n=i(39938),s=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function T(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function _(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,n.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function x(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,n.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,n.notBlank)(t.Make)&&(0,n.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function O(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function A(e){return[...O(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:T},{notVideoTooLong:_},{notRejectedRating:D},{notExcludedKeyword:x}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??A(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=O,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...O(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...O(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...O(e))},t.expensiveFileFiltersFor=A,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const n=r(i(49411)),s=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>n.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(n.default.join((0,t.execDir)(),"resources"),n.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=n.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),n=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,n.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),n=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,a,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),n=i(51081);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function _(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=E(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===h.Timeout&&(0,p.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await _(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?_(e):E(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=_,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const n=r(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return n.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),n=i(43414),s=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>n.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),n=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const n=r(i(87561)),s=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(P(r),P(n));if(null==s||s>1)return"unmatched "+i+": "+r+" โ‰  "+n}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const n=r(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),n=i(6314);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),T=i(8177),_=i(38307),E=i(91641),D=i(95557),x=i(57510),k=i(82341),C=i(35796),F=i(10408),I=i(53525),O=i(18849),A=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,T.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,k.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,n,s,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=n,this.elapsedMs=s,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,A.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),r.add(this),n.set(this,void 0),s.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,n,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,O.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),n={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},s=(0,h.unparse)([n],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(s+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const n=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await r(),a=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:s}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-n,...s,state:a}),s}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-n}),r}}get output(){return l(this,s,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,s,"f");return u(this,s,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,n,"f")}}t.SyncReport=$,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,n,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,x.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,n,"f").nativePath),this.logger.info("Opening new report: "+l(this,n,"f")),M.isTest&&(0,_.stdoutWrite)({syncReport:l(this,n,"f").nativePath},!1),u(this,s,(0,d.createWriteStream)(l(this,n,"f").nativePath),"f"),l(this,s,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,s,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),n=i(43947),s=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function T(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function _(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await T(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=T,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await _(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await _(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=_},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),n=i(14889),s=i(95725);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),n=i(34996);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44470)),s=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),n=i(79403),s=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),T=i(16475),_=i(77125),E=i(66776),D=i(23175),x=i(44726),k=i(20636),C=i(90957),F=i(39784),I=i(82798),O=i(13779),A=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),Z=i(18295),X=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,n,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,n,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,n,"f",l).push((0,x.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,n,"f",l).toA()}static addLoadingMsg(e){v(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,n,"f",h).entriesByCountDesc()}),(0,E.map)((0,O.leastBy)(e,(e=>[v(this,n,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,n,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return v(this,n,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,_.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=n.summary();if(t.settledCountv(n,n,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>n.onResultChange(),onError:()=>n.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,O.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,n=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,n,"f",s),(e=>!e.isPending)),v(this,n,"f",s)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Z.summarizeHealthChecksSync)({errors:v(this,n,"f",l),skipPending:v(this,n,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,n,!0,"f",u),t.state!==v(this,n,"f",c).last?.state&&v(this,n,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=n.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,x.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new A.BoundedList(10)},u={value:!1},c={value:new A.BoundedList(10)},d={value:new A.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(n,n,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(n,n,"m",m).call(n))),Q.resetDebounced=(0,N.debounce)((()=>n.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),n=i(77125),s=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),n=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(70612)),s=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),n=i(88491),s=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),n=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),T=i(4416),_=i(47874),E=i(43414),D=i(96593),x=i(95011),k=i(49312),C=i(36810),F=i(87062),I=i(80870),O=i(14489),A=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,n.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const n=i.sha??await r.sha();if(null!=n)if(!0!==await(0,t.isBadSha)(n))try{return await this._build(r,i)}catch(t){e.push(t),L().set(n,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,A.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:n,width:a,height:o,sha:l,mimetype:u}=t;if(null==n||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,x.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:n,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,s.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),n=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,x.equivalentFitSizes)(r,n)){const a=(0,x.fitSizes)(e,e.mimetype),o=(0,s.diff)(r,n);if((0,s.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const n=new T.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,x.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const s=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),n.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,s=t.outputSize(p??S);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),n.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),n=i(57743),s=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,n.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),n=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:n,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:n,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,n.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,n.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),n=(0,p.splitEvery)(i,3);this.basename=n.pop()+"-",this.parent=e.join(...n)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,r,"m",n).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const n=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=n,await this.writeInfo(t)),n}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,n=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const n=r(i(57441)),s=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;in?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:n.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:n.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),n=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),n=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),n=i(57743),s=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,n.dmegapixels)(a)-(0,n.dmegapixels)(l)>2.5)&&(l=a,r.push([a,s])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),n=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),n=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),n=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),n=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const n=r(i(57441)),s=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),T=i(13378),_=i(27446),E=i(68107),D=i(37251),x=i(34928),k=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function O(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,x.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const s=(0,x.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,_.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:n.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,n.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,n.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,_.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function A(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,T.shim1)({name:"img.imageHash",cache:I,impl:O}),t._imageHash_=O,t.isImageHash=A,t.toImageHash=function(e){if(null!=e){if(A(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(A(t))return t}}},t.HashDim=8},36810:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return s(this,r,"f",n).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,r,"f",n).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,r,"f",n)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(r,r,"f",n).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,n={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),n=i(11944),s=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,n.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,s.assignFields)(i,r.asExifTag()));const n=i?.exposureSettings;null!=n&&(delete i.exposureSettings,i.FocalLength=n.focalLength,i.FNumber=n.aperture,i.ExposureTime=n.shutterSpeed,i.ISO=n.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const n=r(i(57441)),s=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:n.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:n.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(r.map(c)),diffHash:(0,s.flatten)(r.map(d))}}},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),n=i(66776),s=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,n.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),n=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),n=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,a]=e.split("\t"),o=(0,n.toGt0)(s),l=(0,n.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),n=i(57743),s=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const n=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:n,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,n.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,n.fmtDim)(i)} is too small for ${(0,n.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const n=i(889),s=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),T=i(96593),_=i(27446),E=i(84685),D=i(15465),x=i(68107),k=i(53719),C=i(59387),F=i(34928),I=i(71923),O=i(49312),A=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{s.default.simd(M.Settings.enableSIMD.valueOrDefault),s.default.cache(M.Settings.enableVipsCache.valueOrDefault),s.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,T.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof n.BinaryField))return;const l=o.bytes(0,T.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const s=await(0,D.readMimeType)(e);if((0,u.blank)(s))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,x.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,_.isVideoMimeType)(s),S=(0,_.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),A=(0,h.lt)(C,1),L=(0,_.isSharpMimeType)(s)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||A||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:A,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,s=await(0,T.readRawTags)(e,i);if(null==s)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof n.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,s,t,k,C)))}}}(0,_.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(s)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const n=await(0,w.time)("img.read."+i.desc,i);if(null!=n)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:n.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...n};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),n=i(88491),s=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=n.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*n.secondMs},p1:{x:20*o.MB,y:12*n.secondMs}},p={p0:{x:11*o.MB,y:12*n.secondMs},p1:{x:26*o.MB,y:24*n.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,n=(0,f.commandTimeoutMs)(),s=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+n+s+c+d),dbMs:i,tagMs:n,copyMs:s,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,s.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const n=r(i(57441)),s=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),T=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void T().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=T().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&T().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const _=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return _().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:_,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(T().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))T().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,n.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,n.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),n=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),n=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),T=i(43649),_=i(6667),E=i(49586),D=i(43414),x=i(68567),k=i(27947),C=i(96593),F=i(27446),I=i(84685),O=i(68107),A=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),n=D.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,n))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,x.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,T.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,O.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),h=null==d?void 0:await(0,L.dimensions)(n);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:h}),n.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,A.commandTimeoutMs)()}),n.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,n.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const r=j("transcode",e),n=$.get(t.nativePath);if(null!=n&&!(0,s.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:n.name}),n.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),n=(0,k.extractDurationSec)(r),s=(0,k.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,n={src:e,...V(e,d)},s=J(o,n.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,_.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(n.width=(0,u.roundEven)(e.width),n.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));n.dest=i,n.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(n));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),T=i(5023),_=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,x=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function k(){x.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(x(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await x.prior()??x.refresh()},t.isFFmpegSupported=async function(){return null!=await x()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...O(t),...C(t),"-threads",(0,u.toS)((0,T.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,T.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),n=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,n.lazy)((()=>(0,r.toGt0)(s.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),n=i(88491),s=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:n.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:n.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),T=i(33185),_=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return _().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],x=["-o","1"],k=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return _().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(_().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...E,...D,...x,...v,...k,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*s.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};_().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),O=[];function A(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,T.isIgnorableValidationError)(i))_().info("dcraw_emu(): warning",{src:e,msg:i});else{_().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});O.push(r)}}I.on("error",A),I.stderr.on("data",A);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,n.isNotEmpty)(O))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:O,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),n=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),n=i(43414),s=i(69060);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),n=i(11944),s=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),n=i(59694),s=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),T=i(79015),_=i(98462),E=i(43414),D=i(10508),x=i(33501),k=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,k.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function A(e,i,r,n){try{return(0,s.blank)(e)?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=A,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await A(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>_.BaseFile.for(e))),r=(s=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,n.sortBy)(s.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,T.ee)().on("clearCache",(()=>t.m.unset())),(0,T.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),n=i(4866),s=i(39938),a=i(10508);t.l=(0,n.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===n));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,s.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),n=i(39938),s=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),T=i(46573),_=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const x=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,a.defer)((()=>(0,m.thenMap)(k(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(F)))}async function O(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function A(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void x().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,_.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,T.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,O,A,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return x().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),n=i(88491),s=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),b=i(92781);function S(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*n.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),n=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),n=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),n=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,n.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),n=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),n=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?n(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),n=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),n=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),n=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>n(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),n=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),n=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var r,n,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),n=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),T=i(10408),_=i(57400),E=i(3955),D=i(43414),x=i(71951),k=i(85352),C=i(81647),F=i(95976),I=i(9483),O=i(98968),A=i(53208);function L(e){const t=(0,x.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await _.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,O.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,O.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,O.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,O.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await _.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,A.readLogEntries)(e,{start:r,end:i}),(e=>(0,O.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,T.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),n=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),T=i(93033),_=i(40374),E=i(83837),D=i(43414),x=i(74269),k=i(85352),C=i(81647),F=i(95976),I=i(48924),O=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class A extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,n,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,O.recentLogEntries)()),(0,O.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=A,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,T.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,_.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),n=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),n=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,n.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),n=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),n=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),T=i(81026),_=i(27998);t.setupLogger=(0,n.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new T.LogWriter(e));const n=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&n.push(y.ConsoleLogger.instance()),(0,s.map)((0,b.logBroadcaster)(),(e=>n.push(e))),l.rootLoggers.set(n),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,n.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new _.PlaintextLogFormatter)}));const E=(0,n.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,n=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),n=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):r[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),n=i(89965);t.kmeans=function(e,t,i){const s=n(e,t,i);return{...s,centroids:(0,r.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return n(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),n=i(75556),s=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const n=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=n;t(0,n.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,r){const s=new a.Average;return l(t,i,r,(t=>(0,n.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,r){const s=[];return l(t,i,r,(t=>(0,n.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const n=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(n,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,n=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,s.leastIndex)(n)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,n=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,s.greatestIndex)(n)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,n.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),n=i(88491),s=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[n,s,a,o,l]=(0,t.factors)(e),u=(n*i*i+s*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[n,s,a,o,l]=(0,t.factors)(e);return`(((${n}*${i}*${i}+${s}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,n,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,n/o,l/u,c/h].map((e=>(0,s.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:n.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),n=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),n=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},76474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),n=i(3331);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),a(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),n=i(39938),s=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,n.mapNotBlank)(e,(e=>(0,n.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),n=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),n=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,n.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),n=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),n=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),n=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,n.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),n=i(4866),s=i(82798);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),n=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(70612)),s=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),n=i(44726),s=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,n.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),n=i(11944),s=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],n=[];for(const a of t)for(const[t,o]of(0,s.entries)(a)){const s=await o(e);!0===s?i.push(t):!1===s?r.push(t):n.push(t)}return{accepted:i,rejected:r,notApplicable:n}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:s,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,n.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),n=i(86780);class s{static firstFalse(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i))if(!1===n(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i))if(!0===n(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,n]of(0,r.entries)(i)){const i=n(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,n.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),n=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),n=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),n=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),n=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,n.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),n=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),T=i(43414),_=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",T.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,s.mapNotBlankOr)(T.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:T.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,_.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),T.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(T.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,_.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),n=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),n=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),n=i(61570),s=i(84253),a=i(43414),o=(0,s.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,n.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,n.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),n=i(39784),s=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=s.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),n=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(g.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],T={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},_={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?_:T;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),n=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),n=i(4866),s=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,n.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const n=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),n=i(63774);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),n=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,n.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,n.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,n.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,n.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),n=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),T=i(29393),_=i(94794),E=i(7560),D=i(45005),x=i(20902),k=i(6565),C=i(80534),F=i(86613),I=i(15203),O=i(51053),A=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),ne=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>O.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!O.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>O.isMac?"100ms":O.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:_.RepairModes,defaultValue:_.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:O.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,A.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>O.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,A.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(O.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ne.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(n.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(n.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,x.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),n=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>n.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:n.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),T=i(10408),_=i(79015),E=i(98462),D=i(98250),x=i(38846),k=i(23830),C=i(84161),F=i(44911),I=i(43414),O=i(95699),A=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(A.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",H),(0,_.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let n="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(n,i),j().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(n),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(j().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"old"}),await n.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Z(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,T.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,n.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,x.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),n=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),n=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),n=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),n=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),n=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),n=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,o.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),n=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),n=i(91464);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),T=i(50140),_=i(68074),E=i(54809),D=i(64455),x=i(60299),k=i(3955),C=i(95725),F=i(63410),I=i(9483),O=i(43414),A=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,_.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,_.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,_.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,_.datedToLocal)(i.minus(t)),end:(0,_.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],n=r;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||L.OverrideUTCZoneTags.includes(n))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,_.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:a}),a}function q(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,_.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=n("tags",U(t,O.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??n("tags",U(t,O.Settings.capturedAtTagsFallback.values))??(s?void 0:n("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:n("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",q(e,t)))??(s?void 0:n("path",H(e)))??(O.Settings.useStatToInferDates.valueOrDefault?n("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),n=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(889),s=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),T=i(23595),_=i(84593),E=i(21084),D=i(98250),x=i(95725),k=i(76531),C=i(7162),F=i(76474),I=i(19658),O=i(2023),A=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),Z=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),ne=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,A.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,x.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),n=await e.sidecar(),s=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void se().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;se().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(n,"tz","tzSource",...L.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,X.normalizeMimetype),...n},o=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(n))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,O.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(n))),(0,f.assignFields)(a,n),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,O.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,T.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=o?(0,Z.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Z.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,o);if(null==h)return void se().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,_.eqlAsync)(e.sha(),t.sha())||await(0,_.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,x.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,x.toNativePath_)(e),["-"+t]);return(0,O.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[n,s]of(0,f.entries)(t)){const t=await me(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),n=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:n}),await le().write(r.nativePath,n,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[a])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,h.toS)(n)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var n;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function T(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function _({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),a=n(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=T,t.findInequalFields=function(e,i){const r=T(e),s=T(i);if(null==r||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=s[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,n.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>_({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>_({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>_({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>_({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),n=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),n=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),n=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),T=i(95725),_=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>x({action:e,key:t,value:i})))}function x({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=x,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function O(e,i,r){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,T.toNativePath_)(e),a=await(0,E._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,a.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=D(t.Actions.infer,r),s=(_.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return _.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),O(i,n,s)},t.ensureHistoryRecords=O},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,l.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),n=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),n=i(25861),s=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new n.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function T(e){return Array.isArray(e)&&e.every(T)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(T))}function _(e){if(null==e)return[];if(Array.isArray(e)&&e.every(T))return(0,h.flatMap)(e,_);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,_).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=T,t.parseKeywordStruct=_,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(T(i)?t.push(..._(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,n.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),n=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,n.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),n=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,n.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const n=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>n.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,n.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:n}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)n.push(`Revision@${i.createdAt}`),(0,s.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){n.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,s.remove)(e,t)}return{value:e,source:n}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),n=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),n=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),n=i(75556),s=i(43414);function a(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),n=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),n=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),n=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const s=S(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const n=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),n=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(n.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(n.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),n=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),T=i(21084),_=i(98250),E=i(75123),D=i(95725),x=i(9483),k=i(43414),C=i(96879),F=i(69301),I=i(65642),O=i(96593),A=i(17310),L=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,O.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:x.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new T.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(A.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),n=(0,D.findFileIndex)(e,r);if(n<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(n-2*t,n),r.slice(n+1,n+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,O.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),n=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,n.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,n.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),n=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(n,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return _(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new S(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===r&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new S(r,n,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(_(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=_(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function T(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?T:M;let r="";const{scheme:n,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=_;const x=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(x)?e.replace(x,(e=>D(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),n=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),n=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),n=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?a.join(t,...n):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),n=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),n=i(39036);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),n=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),n=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),n=i(55412),s=i(46573);t.currentVolumeRoots=(0,n.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,s.volumes)()){t.push(i.mountpoint);const n=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=n&&e.push(n)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),n=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await O()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const T=/([a-z]+)(?::\\)?/i;function _(e){return e?.match(T)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(_(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(_(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function x(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(_(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function O(){const e=(0,n.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,o.flatten)(t).map(x)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,n.compact)((0,o.flatten)(r).map(I)),l=(0,n.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=O},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),T=i(55412),_=i(62255),E=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,_.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await x(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,n.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,T.setupVolumeTTL)(t.gioVolumes)));const x=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),n=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),n=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...n,...s},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),n=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),n=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),T=i(76531),_=i(51053),E=i(43414),D=i(39206),x=i(36736),k=i(62255),C=i(49829),F=i(10609),I=i(53719),O=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function A(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){A(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(A),E.Settings.scanPaths.watchLater(A),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,x.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,T.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{x.gioVolumes.unset(),A()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:x.GioCommand,args:x.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(x.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),n=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function T(e){return!y.Settings.excludedFilesystemTypes.has(e)}function _(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=T,i=_){if(g.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=E,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),n=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),n=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),n=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>_())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function T(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=T;const _=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?T():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),n=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function T(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function _(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=_(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(T(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=T,t.toVolumeUUID=_,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(70612)),s=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),T=i(91710),_=i(14889),E=i(91464),D=i(46852),x=i(37121),k=i(1629),C=i(14195),F=i(42648),I=i(29405),O=i(20902),A=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),ne=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),se=n.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:se}))),s=new Map;for(const e of n)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const n=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return ne().debug("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function ge(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,U.friendlyname)(e);return(0,D.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,x.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,A.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,T.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,x.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,A.onError)("Timed out getting local volume metadata")));if(null==e)return void ne().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,x.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,A.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),n=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),n=i(11944),s=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),n=i(11944),s=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),n=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),n=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let n=!1;function s(){n&&(n=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return n},t.pause=function(e=!0){!1===e?s():n||(n=!0,(0,r.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),n=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),n.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,w());return t=(0,a.clamp)(1,n,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),n=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),n=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),n=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),n=i(11944),s=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,s.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:n}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,n))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,n.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:n,lazyLoad:s,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(n=(n??[]).filter(u.gt0)).length&&n.push(320);const d=Math.min(...n),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const b=s&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=n.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),n=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),n=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),n=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),n=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),n=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),n=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),n=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,n.isFunction)(e)&&(0,n.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),n=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),n=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),n=i(38625),s=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),n=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,o=await i;if(!(0,n.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),n=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),n=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=n.length;(0,r.filterInPlace)(n,(t=>e(i,t))),t=t||s!==n.length,0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),n=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,n){return!(null==n||!l(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,n.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function T(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return T(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=T,t.toFixed=function(e,t){try{return M(e,(e=>T(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return h(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-T(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?T(e/r)*r:T(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,b(t)?T(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),n=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=b(...i.map((t=>t[e])));return n}function S(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&n(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,a]=(0,c.splitFirst)(i,"."),o=S(t,n);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),n=i(23175),s=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),n=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),n=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),a=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?o.indexOf(r)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),n=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,a=new Set(r??[]);if(t===e&&0===n&&0===a.size&&1===i)return[e];const o=n-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),n=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,n.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),n=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=b(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),n=i(61570),s=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{r&&(0,n.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,n=!0){const s=await o(e,i,n);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const n=i-Date.now();return n<=0?t.Timeout:o(e,n,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return l(e,n,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:n=!0}){const a=await o(e,i,n);return a===t.Timeout?(0,s.tot)(r):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),n=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),n=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),a=d[r];return(0,s.sigFigs)(e/n,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),a=h[r];return(0,s.sigFigs)(e/n,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),n=i(82798);t.ua=(0,r.lazy)((()=>(0,n.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,n)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),n=i(75556);function s(e){const t=e;return(0,n.isNumber)(e)?e:(0,n.isNumber)(t.id)?t.id:(0,n.isNumber)(t.assetId)?t.assetId:(0,n.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,r.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),n=i(39938),s=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),n=i(11448),s=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),n=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),n=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},49374:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),T=i(43414),_=i(82041),E=i(46573),D=i(53719),x=i(59387),k=i(39938),C=i(38625),F=i(88491),I=i(6314),O=i(61570),A=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=T.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",n)?.rootDir.nativePath,i=!0===a(this,r,"f",n)?.isReadySync(),s=!0===a(this,r,"f",n)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!s?a(this,r,"f",n):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",n)),o(this,r,(0,k.blank)(e)||!(0,_._libraryHasSettings)(e)?void 0:new r(e),"f",n))}static get priorInstance(){return a(this,r,"f",n)}static endPriorInstance(){const e=a(this,r,"f",n);return o(this,r,void 0,"f",n),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,s.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,_.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=T.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;T.Settings.maxConcurrentImports.hasValue()||(T.Settings.maxConcurrentImports.tmpValue=e,(0,x.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,O.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>A.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,s,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,s=new WeakMap,n={value:void 0}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),n=i(20902),s=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,s.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=s(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),b=i(91641),S=i(95557),P=i(4691),M=i(52289),T=i(10408),_=i(27519),E=i(49379),D=i(17875),x=i(79015),k=i(12737),C=i(49857),F=i(7157),I=i(85352),O=i(9483),A=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(_.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(_.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,x.ee)().on("fatal",$),(0,x.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,T.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Z))))}function Z(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,A.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=Z,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[O.LogLevels.fatal,"fatal"],[O.LogLevels.error,"error"],[O.LogLevels.warn,"warning"],[O.LogLevels.info,"info"],[O.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),b=i(7162),S=i(33148),P=i(55568),M=i(25516),T=i(38307),_=i(42041),E=i(95557),D=i(4691),x=i(2126),k=i(7383),C=i(70259),F=i(24905),I=i(44731),O=i(20902),A=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Y=i(39938),Z=i(88491),X=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{k.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,x.exit)({reason:"exit() event",status:0})))}));class ne extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,new Q.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,n,(0,b.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,s,"f").promise}get isReady(){return m(this,s,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=ne,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Y.mapNotBlank)((0,O.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Y.mapNotBlank)((0,O.getEnv)("PS_CRASH_"+this.name),(e=>{(0,X.later)((()=>{throw new B.WrappedError(e)}),5*Z.secondMs)})),(0,S.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,s,"f").reject():m(this,s,"f").resolve()}catch(e){console.error((0,A.errorToS)(e)),m(this,s,"f").reject((0,te.toErr)(e)),(0,x.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,A.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,x.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,x.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,x.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,x.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,x.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,T.stdoutWrite)({version:_.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,X.later)((()=>(0,x.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,T.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,T.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,n,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,n,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),n=i(7162),s=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,n.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:s.AssetVersion,AssetFileVersion:s.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),n=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(n.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+n),n):n}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),n=i(85297),s=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,o()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),n=i(92507),s=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,n.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,s.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function T(e){return(0,s.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function _(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),T);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=T,t.dateTag=_,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:_(r.date)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),n=i(43414),s=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...n.Settings.rootTagKeywordsAliases.values,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,s.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...n.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...n.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,s.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,s.tagDiff)(t,e),r=(0,s.tagDiff)(e,t),a=n.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,s.tagRefToS)(e[0]).toLowerCase());return t&&!(0,s.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},18130:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),T=i(79403),_=i(43414),E=i(88491),D=i(75556),x=i(61570),k=i(23175),C=i(6628),F=i(72537),I=i(51603);class O extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,n.set(this,0),s.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),_.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||_.Settings.dbForceRecover.valueOrDefault)&&(T.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),n=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:n,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,x.pick)(this,"schema","dbFile")}get open(){return null!=l(this,s,"f")&&l(this,s,"f").open}get inTransaction(){return this.open&&!0===l(this,s,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,s,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,s,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===_.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(_.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,n,(e=l(this,n,"f"),++e),"f")%_.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,s,"f")?.pragma("incremental_vacuum"),l(this,s,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,k.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,s,"f")?.open&&(this.logger.info("closing db",l(this,s,"f")),l(this,s,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,s,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),n=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,n),i||await(0,y.dbBackupCold_)(n,e),e.join(this.dbFile.base)}}t.Db=O,n=new WeakMap,s=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),T=i(19067),_=i(41593),E=i(94332),D=i(91894),x=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class k extends h.EndableInterval{static for(e){return new k(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",s).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,x),n.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,n,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,_.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,n,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,n,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,T.fmtDuration)(Date.now()-l(this,n,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=k,n=new WeakMap,r=new WeakSet,s=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:x,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),n=i(7162),s=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),T=i(91894),_=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function x(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return k((0,l.pathToDb)(t,"models"))}function k(e){return e.sibling("db-info.json")}async function C(e=x(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw _().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,T.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=x,t.libraryDbInfoFromDbFile=k,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let n,o;await i.tryAcquire_();const u=k(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(n=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==n||null==o){const i=await(0,s.getLiveDbDir_)(e),r=await i.db.uri_();n=i.useReplica,n&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>_().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:n})}})),null==o||null==n)return _().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();n&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!n),(0,T.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw _().error("Failed to set up model db",{error:e}),(0,T.addDbSetupError)(e),i.release(),e}return _().tap({msg:"dbModelSetup()",result:{db:o,useReplica:n,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),n=i(4866),s=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,n.lazy)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:n}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const s=n[i].bind(n);return null==r.bindings?s():s(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),n=i(39938),s=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,s.isError)(e)||!(0,n.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),n=i(7162),s=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,n.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),n=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),s=r[0],l=r.slice(1),u=s?.id;if((0,o.isEmpty)(n)||(0,o.isEmpty)(l)||null==s||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:s,winnerId:u,leafs:n,losers:l});const d=(0,a.splitTagPath)(s._path).slice(0,-1),f=[...d,n[0]];s._path=(0,a.joinTagPath)(f),s.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??s.parentId,h().info("mergeTags()",{winner:s,losers:l,winnerTagPath:f,leafs:n});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:s.parentId,path:s._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:s._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:s,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,s.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,s.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const n=r(i(40514)),s=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,s.lazy)((()=>(0,n.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,n,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),T=i(39938),_=i(88491),E=i(43947),D=i(87748),x=i(66776),k=i(8199),C=i(47025),F=i(91894),I=i(12586),O=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,k.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*_.minuteMs},(()=>a(this,r,"m",n).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),n=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(n);return o?await n.bind(I.Migrations)(this.db):await a(this,r,"m",s).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,n=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(_.secondMs,3*_.secondMs)),await(0,x.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),_.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},s=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,T.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,O.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),n=i(4866),s=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),T=i(82798),_=i(54578),E=i(85476),D=(0,n.lazy)((()=>(0,s.mkLogger)("db.Migrations"))),x=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function k(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>x.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=k,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},k),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const n of t){const t=(0,T.toS)(n.ids).split(","),s=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(s,(e=>[e.shown,e.version,e.updatedAt])),o=s.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:_.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),n=i(4866),s=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),T=i(24603),_=i(87748),E=i(6314),D=i(75556),x=i(26588),k=i(44726),C=i(17078),F=i(39784),I=i(82798),O=i(9069),A=i(70582),L=(0,n.lazy)((()=>(0,s.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,k.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,T.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,_.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,A.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const n=await(0,y.sqliteNativePath_)(),s=await(0,r.thenElapsed)((0,a.stdout_)(n,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+s.elapsedMs+"ms",s.result),s.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,O.modelDb)()?.end()),await(0,A.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const n="wal_checkpoint("+r+")",[s]=(0,F.toA)(t.pragma(n));return L().info("checkpoint()",{pragma:n,result:s}),(0,D.gt0)(s?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):s};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),n=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),s=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},n),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:n});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:n});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),s.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,x.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,x.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),n=i(1058),s=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,s.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,s.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,n.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),n=i(89253);function s(e){const t=new n.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=s,t.localTableInfo=function(e){return s(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),n=i(43414),s=i(82798);t.withDbSync=function(e,t,i=n.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,s.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=n.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,s.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},32159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(97742),n=i(7162),s=i(37980),a=i(37445),o=i(10408),l=i(98250),u=i(72461),c=i(3874),d=i(11944),h=i(39938),f=i(38625),m=i(87748),p=i(61570),g=i(7127),y=i(49374),v=i(20990),w=i(92045),b=i(18273),S=i(66056),P=i(30690),M=i(50725),T=i(66953),_=i(63216);!async function(){try{const e=new s.CLI(g.ServiceNames.list).add(w.LogArgs,a.WriteSettingsArg);e.add({beforeParse:e=>e.option("--reindex","Rebuild the fulltext search indexes before running any query.").option("--query ","Apply the given query and return all matching asset file paths. Must be the last argument. Incompatible with --where.").option("-j, --json",'Emit a JSON object for every asset file with "hidden" and "shown" flags').option("--dump","Emit a JSON object that includes all column values").option("--where ","Apply a SQL WHERE clause to filter the rows returned.").option("--orderby ","Apply a SQL ORDER BY clause to filter the rows returned.").option("--looks-like ","Find images that look like the photo or video specified by FILE. Use a full pathname.").option("--tags","List all tag paths along with their counts.")});const t=(await e.parse()).opts(),i=(0,d.mapNotEmpty)(t.query,(e=>e.join(" "))),r=(0,f.isTrue)(t.dump),o=r||(0,f.isTrue)(t.json),E=t.where;if(null!=i&&(0,h.notBlank)(E))throw new Error("--query cannot be used with --where");const D=t.order,x=new v.Service({name:"list"});await x.ready;const k=await y.Library.instanceRequired().modelDb();(0,f.isTrue)(t.reindex)&&await(0,_.forceRunTagMaintenance)();const C=(0,n.mkLogger)("list");if((0,f.isTrue)(t.tags)){const e=M.Tag.ops().allf((e=>M.Tag.orderBy(e)));return void console.log((0,m.stringify)(e.map((e=>(0,p.pick)(e,"path","assetCount")))))}let F=P.Asset.query().join("AssetFile","AssetFile.assetId","Asset.id").join("AssetTag","AssetTag.assetId","Asset.id");if(F=F.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",shownFile:"AssetFile.shown",mountpoint:"AssetFile.mountpoint",uri:"AssetFile.uri",hidden:"Asset.hidden",rating:"Asset.rating"}).distinct(),(0,h.notBlank)(t.looksLike)){const e=l.PosixFile.for(t.looksLike);C.info("Calculating image hash for "+e);const i=await e.sha(),r=await(0,u.imageHash)(e);if(null==r)throw new Error("Failed to generate image hash for "+e);C.info("Looking for assets with matching meanHash or SHA",{meanHash:r.meanHash,SHA:i}),F=F.where((e=>e.where("AssetFile.meanHash",r.meanHash).orWhere("AssetFile.sha",i)))}r&&(F=F.select((0,b.knex)().raw("AssetFile.*"),(0,b.knex)().raw("Asset.*"))),F=(0,h.notBlank)(E)?F.andWhere((0,b.knex)().raw(E)):P.Asset.shownUnhidden(F);const I=(0,h.notBlank)(D)?D:"uri",O=null!=i?(0,T.queryStringToSql_)(i,F).orderByRaw(I):F,A=(0,S.toSqlQuery)(O);C.info("Running SQL query...",{sq:A});const L=Date.now(),R=k.prepare(A.sql).iterate(A.bindings);C.info("query took "+(Date.now()-L)+"ms");for(const e of R){const t=await(0,c.uri2nativePath)(e.uri,e.mountpoint);o?console.log((0,m.stringify)({path:t,...(0,p.omit)(e,"id")})):console.log(t??e.uri)}}catch(e){console.log("Failed: "+(0,o.errorToS)(e)),(0,r.exit)(1)}finally{(0,r.exit)(0)}}()},30690:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),T=i(38625),_=i(9381),E=i(87748),D=i(66776),x=i(75556),k=i(26588),C=i(39784),F=i(49374),I=i(18290),O=i(89452),A=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),n=await(i?.mtimeMs());null!=i&&null!=r&&null!=n&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:n,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?n.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,x.gt0)(e)?n.ops().firstf((t=>n.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??n.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return n.ops().count(n.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),s=n.ops().findById(e);if(null==s)return void r.warn("asset not found");const a=s.isActive(),o=s.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=O.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),n.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await n.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,n,"m",s).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,n,"m",s).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,n,"m",s).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=n.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),n.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,A.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const n=new O.AssetFile;return this.addAssetFile(n),!0!==t?.skipUpsert?await n.upsertIfNeeded_(e):await n.setFile_(e),n}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=n.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const n=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(n,1),n}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=n.dbl.all(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const n=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==n.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:n});const s=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=s){this.capturedAtLocal=s.capturedAtLocal,this.rating=s.rating,this.durationMs=s.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,k.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const n=!0;this.imgAttrs.set(t,await r.imgAttrs(t,n,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,_.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,k.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,n=W,r=new WeakSet,s=function(){return n.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=n.dbl.first(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=n.dbl.first(n.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),T=i(31053),_=i(43414),E=i(65642),D=i(27446),x=i(3874),k=i(19209),C=i(25116),F=i(36974),I=i(22356),O=i(11944),A=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),Z=i(13222),X=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>k.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Z.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=s(this,r,"m",n).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return _.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=_.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,q.assignAllFields)(this,(0,q.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=s(e,r,"m",n).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,T.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),n=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>n.push(e))),this.isVideo)return n;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return n;const s=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,T.previewToDownloadable)(i.base,e)))));return n.push(...(0,O.uniqBy)(s,(e=>e.size))),n}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=k.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=k.URI.parse(this.uri),n=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:n};function s(){return(0,A.at)((0,A.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(s(),(0,A.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&s()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=k.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:s(),thisVolSha:t}),s()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:s()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:n}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,n=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?_.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),n=i(75556);t.toAssetId=function(e){const t=(0,n.toGt0)(e?.assetId)??(0,n.toGt0)(e?.id);if(null==e||null==t||!(0,n.isNumber)(e?.capturedAtLocal))return;const i=((0,n.toGt0)(e.v)??(0,n.toGt0)(e.updateCount)??(0,n.toGt0)(e.updatedAt)??0)%1e6,s={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,n.gt0)(e.durationMs)&&(s.durationHMS=(0,r.durationHMS)(e.durationMs)),s}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),n=i(2934),s=i(7907);class a extends s.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,n.parseJSON)(this._priorValueJson)}get newValue(){return(0,n.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class n extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=n,n.$tableName="AssetTag",n.$uniqueColumnName="assetId,tagId",n.$useCache=!1,n.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),n=i(7162),s=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,n.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,s.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),n=i(7383),s=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,n.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,n.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{s.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const n=i(47261),s=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,s.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[n.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const n=this.class(),s=(0,l.notEmptyOr)(r,n.ops().columnNames());return(0,h.fromEntries)(s.map((t=>this._get(t,e,i))),t?{$ctor:n.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,s.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),n=i(82341),s=i(4866),a=i(66776);t.modelDb=(0,s.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,n.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),n=i(11944),s=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[s,o]of Object.entries(t)){if("$ctor"===s)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(s,i);e[t]=null==o?o:(0,n.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,s.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,n.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,n){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${n}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:n,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,n,s,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),T=i(39938),_=i(24603),E=i(1429),D=i(87748),x=i(66776),k=i(75556),C=i(61570),F=i(39784),I=i(78650),O=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,n.set(this,void 0),s.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,n,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,O.addModelClass)(e),d(this,s,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,s,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,k.gt0)(e)&&h(this,s,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,x.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(k.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,k.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,n,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),s=this.dbl.runf((e=>e.insert(i)));return t.id=(0,k.toInt)(s.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,x.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,T.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,T.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),n=this.findOneBy(t);return h(this,r,"m",l).call(this,i,n),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,n,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),n=[];for(const s of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(s.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,_.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),n.push(e)}}return n}delete(e){const t=(0,F.toA)(e).filter(k.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,s,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const n={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(n);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),n=i(4866),s=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,n.lazy)((()=>(0,s.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const n=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=n)return void c().debug("applyOnce(): already done",{priorCompleted:n});const s=this.ops().insertOne(e),o=await t(s);return(0,r.ending)()||s.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),n=i(97742),s=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),T=(0,s.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,s.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const _=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),D.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return T().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return T().tap({msg:"times()",result:this.dbl.all({sql:_,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?T().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:n.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),n=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class s extends n.TimestampedModel{}t.ProgressMeta=s,s.$tableName="ProgressMeta",s.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),n=i(7162),s=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,n.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,s.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),T=i(26588),_=i(44726),E=i(39784),D=i(17078),x=i(52465),k=i(18273),C=i(66056),F=i(54578),I=i(30690),O=i(14405),A=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,_.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,k.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,_.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=s(this,r,"m",n).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,n=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:n});try{if(null==n)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,k.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=n._path,this.logger().info("changePath(): replacing with sibling",e),A.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:n.id}))),A.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...n.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:n.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,T.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,_.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(O.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,_.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,n]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(O.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(O.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,n=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(x.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),n=i(59553),s=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,n.tag_fts_root)(e._path),path:(0,n.tag_fts_path)(e._path)})));(0,s.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const n=c.$tableName;this.dbl.runScript([`INSERT INTO ${n}(${n}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),n=i(7162),s=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,n.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=s.Settings.minStreamCorrPct.valueOrDefault/100,i=[],n=e.filter((e=>e.length>5));for(const e of n){const n=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==n?i.push(e):n.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),n=i(11944),s=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(s.gt0);return(0,n.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,s.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},77837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(23595),n=(0,i(4866).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return n().parse(e)}},26825:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(11944),n=i(39938),s=i(38625),a=i(44726),o=i(82798);function l(e){return"object"==typeof e&&(0,n.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,s.isTrue)(e?.not)?(0,s.isFalse)(e?.term):(0,s.isTrue)(e?.term)},t.SetQuerySymbols={not:"ยฌ",and:"โˆง",or:"โˆจ"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,s.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},40234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(13779),n=i(11254),s=i(11944),a=i(59694),o=i(39938),l=i(38625),u=i(84253),c=i(82798),d=i(77837),h=i(26825);function f(e){return(0,a.sortBy)((0,s.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[ยฌ(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[n,s]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(s,(e=>e.type===t.type));for(const e of a)n.push(...e.queries);const l={type:t.type,queries:f([...n,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:n.TagRoots.Keywords,keyword:n.TagRoots.Keywords,keywords:n.TagRoots.Keywords,dir:n.TagRoots.fs,directory:n.TagRoots.fs,folder:n.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},4728:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const n=r(i(50764)),s=i(4866),a=i(7162),o=i(19658),l=i(53525),u=i(75556),c=r(i(12436)),d=(0,s.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new n.default.Parser(n.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!o.isProd&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},66953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(4866),n=i(7162),s=i(85590),a=i(68074),o=i(6667),l=i(43414),u=i(61473),c=i(39938),d=i(38625),h=i(87748),f=i(82798),m=i(18273),p=i(30690),g=i(77837),y=i(26825),v=i(40234),w=i(4728),b=(0,r.lazy)((()=>(0,n.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const n="Asset.updatedAt"===r?s.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=n(l),c=l?.following()?.toDateTime(),d=n(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",M(t));case v.AssetTermNs.excluded:return _({qb:e,column:"Asset.excludedAt",whereNull:0===M(t)});case v.AssetTermNs.deleted:return _({qb:e,column:"Asset.deletedAt",whereNull:0===M(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),n="="===t.op,s=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const n=i[r];return i[r]=t.get(n)??n,i.join("/")}(t,i);if(r||n)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+s.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(n?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+T(s.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+T(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function M(e){return P(e)?1:0}function T(e){return e.includes("*")?e.split("*").map(T).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function _({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},12436:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function n(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const s=r(i(34235)),a=i(11944),o=i(82798);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=s.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-ยฌ]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|โˆจ|\|{1,2}) +/,and:/(?:and|AND|And|โˆง|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:n},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:n},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:n},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:n},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:n},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:n},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),n=i(55568),s=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,n.isStatsDbMigrator)()&&(await t.migrate_(),new s.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},97840:function(e,t,i){"use strict";var r,n,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),T=i(39784),_=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(_.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,T.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",n).call(this,e);return null!=t&&(await l(this,r,"m",s).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),n=await e.posixFile_();null==n&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(n);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",s).call(this,n,e),h=null!=await l(this,r,"m",o).call(this,n,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:n.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(n);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===n.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+n.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,n=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),n=await this.findLibraryFileWithSameContents(e,r);if(null!=n)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:n}),n;const s=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:s,dest:r}),e.copyFile_(s)},s=async function(e,t){const i=await e.existingSidecars(),n=[];for(const e of i)n.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(n)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),n=i(7383),s=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,s.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,n.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,n.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const n=r(i(49411)),s=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),T=i(19067),_=i(75556),E=i(8199),D=i(44726),x=i(11254),k=i(89452),C=i(50725),F=i(21250),I=i(54578),O=(0,s.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,s.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return O().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const A=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:A,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),n=O().addContext(".runTagMaintenance()");n.info("starting",{ctx:i});try{n.info("validating all tags..."),C.Tag.validate_(),n.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(n.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),n.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),n.info("vacuuming orphan tags..."),await L()}catch(e){O().warn("runTagMaintenance() failed",e)}const s=Date.now()-r,a=(0,_.clamp)(A,15*P.minuteMs,20*s);t.runTagMaintenance.setMinCallDelayMs(a),O().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:s})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([x.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(x.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===x.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,T.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:n.default.sep,suffix:n.default.sep}),n.default.sep):k.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},34235:e=>{"use strict";e.exports=require("moo")},50764:e=>{"use strict";e.exports=require("nearley")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=32159);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/logcat.js b/bin/logcat.js index 798f0dc..aa8b7a3 100755 --- a/bin/logcat.js +++ b/bin/logcat.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),f=i(8199),h=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,f.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,f.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,h.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,h.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,h.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,f.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,h.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,h.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,h.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),f=i(92661),h=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,h.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,f.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),f.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(4866),r=i(9678),s=i(15203),a=i(51053);t.EditionType=(0,n.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),f=i(82798),h=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new h.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,f.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class f{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const h=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new f(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(h().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),f=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==f)this.skippedHeaders.push(m),h().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:f});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=f}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function f(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return f(e?.lat,e?.lon,t)},t.geohash=f,t.geohashNumericShort=function(e,t){return m(e,t,30)};const h=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?h.zip([t,e],l(i)):void 0}function p(e,t=o){return h.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),f=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),h={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{f(),(0,a.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,h,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new f(e,t)};class f extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),f=i(29405),h=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,f.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,h.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),f=i(10347),h=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,h.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,f.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function f(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function h(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=f,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=h,t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),f=i(13779),h=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,f.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,h.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),f=i(13779),h=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,h.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,a.lazy)((()=>(0,f.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),f=i(75556),h=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),F=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,f.gt0)(i)&&(0,f.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,f.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,f.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,f.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,f.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,f.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),a.push(R(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,f.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,h.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,f.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,f.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=z,z.instance=(0,o.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new z(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return z.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>z.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),z.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,o.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,f.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,h.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,h.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,f,h=!1,m=0;t=Math.ceil(t);const p=[];function g(){return h||m>Date.now()}function y(){if(null!=f){const e=f;f=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return f=r,(0,n.delay)(1).then((()=>e))}return async function(...n){h=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){h=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{f=void 0},v.donePromise=()=>{if(!h)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(f=void 0,h&&await v.donePromise(),h=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:h,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),f=i(44726),h=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,f.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(h.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!h()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||f(e)},t.isMainService=d,t.isWebService=f,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=h,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||f()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=n.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let o;const l=async i=>{const n=Date.now(),r=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function f(e,t){return h({obj:e,ready:t,stream:r.default.stdout})}function h({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=f,t.stderrWrite=function(e){return h({obj:e,stream:r.default.stdout})},t.writeTTY=h,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);f(t)},t.stdoutWriteMigration=function(e){return f({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>f({shutdownSync:!0}),restartSync:()=>f({restartSync:!0}),forceRestartSync:()=>f({forceRestartSync:!0}),rebuildLibrary:()=>f({rebuildLibrary:!0}),shutdown:()=>f({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),f=i(82798),h=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,f.toS)(e),t=(0,f.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,f.toS)(e).indexOf((0,f.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(f.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,f.toS)(e),t=(0,f.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,f.toS)(e),r=(0,f.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,f.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,f.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,f.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,f.toS)(e))},t.capitalize=function(e){return e=(0,f.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,h.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,f.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,f.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,h.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,f.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,f.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,f.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(f.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),f=i(2023),h=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,f.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,h.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const h=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){f(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),f(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,h.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const f=/^[\da-z]{9}-[\da-z]{7}$/i;function h(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return f.test((0,a.toS)(e))},t.tsFromUid=h,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>h(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),f=i(14889),h=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,h.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:f.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,f,h]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,f,h/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),f.set(this,void 0),h.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,h,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,h=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,f,"f")&&(v.default.clearTimeout(p(this,f,"f")),g(this,f,void 0,"f")),(0,M.gt0)(e)&&(g(this,f,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,f,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,o,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,o,"f")===T.PromiseStates.pending){(0,P.map)(p(this,f,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),f=i(91641),h=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return f.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,h.setEnding)(!0),w();for(const t of f.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of f.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),f=i(66776),h=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,h.toInt)(e)??0,t=(0,h.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const f=()=>{u(this,n,"a",l)&&(0,h.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,h.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),f())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):f(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,f.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,f.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),f=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,f.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),f=i(43414),h=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{f.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,h.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,o,"f")}unset(){f(this,s,0,"f"),f(this,r,void 0,"f"),f(this,a,void 0,"f"),f(this,o,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===n&&f(this,a,i,"f"),d(this,o,"f")?.id===n&&!(0,h.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{f(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){f(this,r,Date.now(),"f");const t=d(this,o,"f");return f(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),f=i(90957),h=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,f=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(f).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,f.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,h.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),f=i(94383),h=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new f.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new h.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const h=f(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new h.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let f=!1;const h=null==t?void 0:t+Date.now();let m=1;for(;null==h||Date.now()t/2&&!f&&(f=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return f||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),f=i(79015),h=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,o.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,f.ee)().on("clearCache",e),(0,f.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,h.childProcLocale)():{},...T(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),f=i(75556),h=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,h.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const a=new Date,o=[];return(0,b.niceable)(i,n)&&o.push((0,_.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,f.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&I(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,f.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,h.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,f.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,f.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(a.stdin);const S=new d.Latch;null==a.stdout?S.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==a.stderr||r?b.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),f=i(4866),h=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,h.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,f.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,h.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function f(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(f(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return a.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=f},37980:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(7304),r=i(97742),s=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),f=i(51053),h=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,h.addFooter)(n.program.description((0,m.cliWrap)(h.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:f.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const n=i(43414),r=i(66776),s=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,s.isEnvTrue)("NO_COLOR")&&(n.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>n.Settings.logColor.envValue=e))}}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,a.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),f=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function h(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=h,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?h(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),f=["year","month","day","hour","minute","second","millisecond"];class h{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:h.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new h(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=f.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new h(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=h},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),f=i(44726),h=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,h.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,f.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=T(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function O(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const f=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),h=(0,o.lt0)(f[0])?[f[0],...f.slice(1).map((e=>-e))]:f;return(0,c.sum)(h)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),f=i(1058),h=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:f,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!h.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==f))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:f??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,f.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,f.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),f=i(80294),h=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,f.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=h.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(h.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),f=i(65113),h=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,f.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${T(s)}:${T(a)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function F(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(F(e,t),l.dayMs)},t.diffMillis=F,t.closeTo=function(e,t,i){return(0,u.mapOr)(F(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(n+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(f.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,E.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),f=i(21040),h=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,h.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,f.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>I(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=F;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(N)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,h.toInt)(t.year),month:(0,h.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,h.toInt)(t.day)})}}const N=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),f=i(93125),h=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):h.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),a=i(36218),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),f=i(82798),h=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,h.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,f.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),f=i(70283),h=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,h.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,f.within)(k(),C(),e)}function F(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,f.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||F(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=F,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),f=i(70283),h=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,f.mapGte0)((0,h.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,o.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[a.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function f(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:f(),desc:"config"})},t.desktopConfigDirs=f},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),a=i(43414);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),f=i(43414),h=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,h.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,h.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,h.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,h.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(f.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),f=i(15203),h=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,f.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:h.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),f=i(83486),h=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,f.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,h.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),f=i(29405),h=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(h.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=m,(0,l.later)((()=>{f.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),f=i(24945),h=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,h.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new f.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function f(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=f;const h=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!h.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(f(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),f=i(53525),h=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,h.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const f=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===f?"error":"warn","onError()",{event:f,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+f.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),f=i(91464),h=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,f.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,f.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,h.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,f.dedupeNeedle)(i,n,"file")),(0,h.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,f.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),f=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(f.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function a(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),z=i(70283),V=i(55568),j=i(14889),B=i(45113),W=i(3917),U=i(31329),q=i(37086),G=i(34996),H=i(36079),$=i(91641),J=i(95557),Z=i(17354),K=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),fe=i(79015),he=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,B.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,fe.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,V.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,Z.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,z.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),E.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",h).call(this,e));r&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",f).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,V.isSyncService)()?(0,he.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new G.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,V.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,K.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:j.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},f=function(e){if(!(0,V.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,he.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,he.setIsSyncing)(!1)},h=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,H.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,V.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),f=(0,a.lazy)((()=>s.default.getgroups?.()));function h(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?h(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?h(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:f()??[],l=0===a,u=l||e.uid===a,h=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(h?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(h?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(h?8:0)|1)&e.mode)))}t.canAccessSync=h,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),f=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,f.resolve)(...e)}};const h=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,f.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:h().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,f.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=h(i(49411)),v=h(i(97742)),w=i(76402),S=h(i(47261)),b=h(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),z=i(13779),V=i(34996),j=i(46852),B=i(7383),W=i(21142),U=i(83486),q=i(49379),G=i(79015),H=i(79378),$=i(7162),J=i(6667),Z=i(51053),K=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),fe=i(35008),he=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,he.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,j.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,z.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,he.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,fe.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),f(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,K.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,j.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,j.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,j.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,he.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,B.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&f(this,a,void 0,"f"),f(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&f(this,a,void 0,"f"),f(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,j.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,j.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,j.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,j.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,j.thenMap)(this.statTimes(),z.max)}maxStatDate(){return(0,j.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,j.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,j.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,j.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,j.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,j.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,j.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,j.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,j.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,j.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,j.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,j.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,H.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,H.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,j.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,j.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,K.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,B.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new V.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,j.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new V.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,K.equalsIgnoreCase)(e.basename,this.base))),t=(0,z.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),a=i(3955);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const f=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function h(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return f().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return h((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=h,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),f=i(3955),h=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,h.toNativePath_)(e);await(0,f.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),f=i(39784),h=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,h.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,f.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,f.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),f=i(79015),h=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends h.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,f.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,f.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function f(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function h(e,...t){return e=f(e),t.some((t=>f(t)===e))}t.normalizeExt=f,t.isExt=h,t.isJpegExt=function(e){return h(e,...u.JpegExts)},t.isJsonExt=function(e){return h(e,"json")},t.isCsvExt=function(e){return h(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return h(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),f=i(98250),h=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,h.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(f.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),z=i(91641),V=i(95557),j=i(4691),B=i(17354),W=i(53525),U=i(9483),q=i(6231),G=i(53719),H=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(H.PsLockExt)+"$");class Z extends V.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??z.EndableRanks.postdb,(0,G.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),f.set(this,Date.now()),this.tryAcquire_=(0,B.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,H.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,H.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",h).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,j.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=Z,r=Z,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,n=new WeakSet,h=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,f,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,f,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,H.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},Z.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new Z(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),a=i(95725);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const f=d(i(44470)),h=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&h.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=h.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",o).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",o).call(this):!a&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(){const e=await(0,b.thenOrTimeout)(f.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function f(e,t={aggressive:!0}){return h((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function h(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:h(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=f(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=f,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=f(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),a=i(76402),o=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),f=i(24588),h=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,h.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,f.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(f.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),f=i(98462),h=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new h.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,f=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function h(e){return null!=f?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":h(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=h,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),f=i(94488),h=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new h.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===f.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,f.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const n=await Promise.race([E(e,t),x(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,f.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===f.CACHEDIR_TAG&&await(0,f.isCachedirTagFile)((0,a.join)(e,n.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,f.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),f=i(13779),h=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,h.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),f=i(82798),h=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,h.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,f.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),f=c(i(87561)),h=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),z=i(69317),V=i(14195),j=i(53525),B=i(49379),W=i(9483),U=i(6231),q=i(51053),G=i(49586),H=i(71663),$=i(43414),J=i(78362),Z=i(3874),K=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),fe=i(76333),he=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,Z.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>K.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,z.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,Z.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,V.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,V.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),K.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,fe.WipPrefix))}isWip(){return this.name.startsWith(fe.WipPrefix)}async wipIsRecent(e=fe.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,fe.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,B.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,he.zpipe_)(this.nativePath,f.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await h.default.copyFile(this.nativePath,n.nativePath,f.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await H.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,H.pwshQuote)(this.nativePath)} -Destination ${(0,H.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,z.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,z.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),f=i(40786),h=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,f.hasChildrenSync)(t,e))return t;for(const i of(0,f.ancestors)(t).slice(0,4)){if((0,f.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,f.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,h.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),f=i(20636),h=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=T(e),r=await(0,f.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===f.Timeout&&(0,p.onTimeout)({soft:!1}),r!==f.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new h.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),f=i(13594);function h(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:h(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=h,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return h(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(h(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,f.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function f(e){return null==e||e.isFile()&&0===e.size}function h(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:f(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=f,t.isDirectorySync=h,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(h(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class f extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=f,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),f=i(9288),h=i(27175);function m(){return(0,a.map)(h.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,f.pathIfExists)(m()?.join("bin",e))),(()=>(0,f.pathIfExists)(m()?.join(e))),(()=>(0,f.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,f.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),f=i(95725),h=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,f.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,f.dirname)(t.file));const o=(0,s.lazy)((()=>(0,h.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),f=i(39784),h=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,h.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,f.toA)(e))try{null!=i&&await o.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function f(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=f,t.writeTextSync_=function(e,...t){return f(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),f=i(7162),h=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,f.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new h.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),f=i(95487),h=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,f.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,h.hasPacman)()&&(i=(await(0,h.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),f=i(43414),h=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:f.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,h.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(f.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),f=i(10742),h=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,h.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{h.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,f.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),f=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),h=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return h().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?f().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):f().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>h.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?h.prior()?.clear():h.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{f().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:f().test(t)||!d().test(t),meta:{err:e,allow:f().test(t),block:d().test(t),validationErrorAllowlist:f().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),f=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>f.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),f=i(19658),h=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),F=i(68107),L=i(53719),A=i(7218),N=i(49441),R=i(12737),z=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function j(e){return f.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,R.ffmpegVersion_)()}function B(e,i){const n=V("extractMaxBitrate",e),r=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,h.mapGt0)(s,(e=>(0,h.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=j,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await j())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,R.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,N.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,F.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),f=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=f&&(null==c||f.height===c.height&&f.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:f}),r.nativePath;const h=(0,k.extractDurationSec)(l),m=Math.min(h??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:h}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,R.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,R.isFFmpegSupported)()}async function H(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,O.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=H;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await G())return;const n=V("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await H(e))return void n.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...B(e,d)},s=J(o,r.videoBitrateKbps,i),a=x.Settings.transcodeMaxDim.valueOrDefault,f=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(f,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const a=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,R.ffmpegTranscode_)(r));0!==o.code&&n.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,R.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),f=i(70283),h=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,h.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,f.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...F(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,a.maxCpus)()/4))))},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),f=i(95976),h=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,h.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,f.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),f=i(4691),h=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,f.ending)()||!0===e?.aborted){const t=(0,f.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,h.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),f=i(55568),h=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,f.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>f.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,h.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),f=i(75556),h=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,f.toInt)(t);return(0,o.blank)(e)||!(0,f.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),h.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,f=4){if(null==i)return null;if(f<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,f-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,f-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),f-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,f-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),f=i(65628),h=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(n.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),r.set(this,!1),s.set(this,!1),a.set(this,!1),this.from=(0,h.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,f.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,f.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,n,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,r,!0,"f")})),this.stream.on("end",(()=>{u(this,r,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,r,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,r,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,n,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,n,"m",l).call(this),t}},r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(e){if(null===e)u(this,r,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),f=i(8199),h=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),F=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,h.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,f.gte)(n,i))return;await(0,h.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const f=d(i(87561)),h=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),F=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,I.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,h.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=f.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),f=i(29405),h=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,h.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,f.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},47065:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Recent=void 0;const r=n(i(97742)),s=i(84492),a=i(11944),o=i(59694),l=i(88491),u=i(43947),c=i(1429),d=i(66776),f=i(75556),h=i(8199),m=i(7127),p=i(2126),g=i(46852),y=i(37980),v=i(64063),w=i(42885),S=i(98462),b=i(51081),P=i(57400),M=i(40374),_=i(94329),E=i(71951),T=i(77200),x=i(13755),D=i(53208),k=i(70283),C=i(43414),O=i(82041);let I;function F(e){r.default.stdout.write(e+b.Newline)}async function L(e){const t=S.BaseFile.for(e);if(await t.isFile())return[t.nativePath];if(await t.isDirectory()){const e=await t.descendants((e=>e.ext.startsWith(".log")));return e?.map((e=>e.nativePath))}}t.Recent={beforeParse:e=>e.option("--recent [duration]",'Automatically cat recent logs. The optional "duration" argument can either be a number, which will be interpreted in minutes, or an ISO 8601 duration string, like "1d" for 1 day, or "20m" for 20 minutes. Defaults to 1 day.'),afterParse:e=>{null!=e.recent&&(!0===e.recent?I=l.dayMs:(0,k.mapGt0)(e.recent,(e=>I=e*l.minuteMs))??(0,w.decodeDuration)(e.recent))}},async function(){const e=await new y.CLI(m.ServiceNames.logcat,"[FILE_OR_DIR...]","FILE_OR_DIR may be either a logfile or a directory that will be scanned for .log, .log.gz, and .log.bz files.").add(t.Recent,v.ColorArgs).parse();r.default.on("SIGINT",(()=>(0,p.exit)({reason:"SIGINT",status:0}))),r.default.on("SIGTERM",(()=>(0,p.exit)({reason:"SIGTERM",status:0})));const i=(0,a.uniq)((0,c.flatten)(await(0,g.mapAsync)({name:"parseArgs",arr:e.args,f:L})));if((0,f.gt0)(I)){const e=(0,M.matcherForExtOrCompressedExt)(".log");await(0,O.readSystemSettings)();const t=Date.now()-I;await S.BaseFile.for(C.Settings.logDir.valueOrDefault).visitDescendants((async n=>{const r=await n.maxStatMs();e(n.ext)&&await n.isFile()&&(0,h.gt)(r,t)&&i.push(n.nativePath)}))}const n=(0,E.DefaultLogFormatter)();if((0,a.isEmpty)(i))return(0,a.isNotEmpty)(e.args)&&(console.error(n.format("error","logcat","No valid logfiles were provided.")),e.help()),F(n.format("info","logcat","No log files provided: reading from stdin.")),F(n.format("warn","logcat","The output will not be sorted chronologically.")),void await s.promises.pipeline(r.default.stdin,new _.LineReader,new s.Transform({transform(e,t,i){(0,d.map)((0,D.chunkToLogEntry)(e),(e=>F(n.formatLogEntry({from:"",...e})))),i()}}));const l=await(0,g.thenCompact)(i.map((async e=>{const t=await P.DirectoryEntry.for(e);return null!=t&&(0,f.gt0)(t.size())?new x.LogReader(t,console.error):void 0})));function w(){let e;(0,a.filterInPlace)(l,(e=>!e.complete()));for(const t of l){if(!t.ready())return;const i=t.peek();null!=i?.ts&&(null==e||i.tse.f.nativePath))));l.length>0;)try{const e=w();if(null!=e)for(const t of e)F(n.formatLogEntry(t));else await(0,u.delay)(10,!1)}catch(e){console.error("caught error",e)}r.default.stdout.write(b.Newline,(()=>(0,p.exit)({reason:"",status:0})))}()},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),f=i(39784),h=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,h.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,f.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,f.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function f(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=f(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=f,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),f=i(8177),h=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new h.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,f.intersection)(e,t).size/(0,f.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),f=i(70283),h=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:h.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),f=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),f=i(53719),h=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return h().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(h().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class f extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=f},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),f=i(7162),h=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,f.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(h.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(4866),r=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),f=i(18226),h=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,n.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){T(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&x()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,f.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},E={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?E:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?h.ColorDistanceFunctions.cie76:h.ColorDistanceFunctions.ciede2000}function x(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=x},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),f=i(71756),h=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,h.tot)(this.optsOverrides.defaultValue)??(0,h.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,h.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,f.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,h.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,h.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,h.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),f=i(84253),h=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),z=i(98788),V=i(61659),j=i(40185),B=i(32994),W=i(39036),U=i(86115),q=i(36738),G=i(17679),H=i(75153),$=i(1440),J=i(92187),Z=i(79660),K=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),fe=i(39165),he=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new he.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new he.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new he.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new he.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new he.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new he.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new he.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new he.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new fe.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:G.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new he.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new K.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new Z.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new fe.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new he.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new he.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new he.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new he.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new he.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,H.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new he.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new he.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,H.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new fe.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,h.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new fe.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new K.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*h.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*h.GB}),validateJpegImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:j.NameTagFormats["as-is"],strEnum:j.NameTagFormats}),tagNamesDefaultFamily:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:B.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),f=i(82166),h=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,f.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(h.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),f=i(51367),h=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),E=i(79015),T=i(98462),x=i(98250),D=i(38846),k=i(23830),C=i(84161),O=i(44911),I=i(43414),F=i(95699),L=i(85560),A=i(98024),N=i(13060),R=i(31086),z=i(16704),V=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,M.libraryDataDirPosixFile)(e)?.join(L.SettingsToml)}async function B(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,N.readTomlFile_)((0,A.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function q(e){return(0,m.map)(j(e),(e=>J(e)))}function G(){t.libraryHasSettings.refresh()}function H(e){const t=j(e);return V().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await B(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=B,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Y()},t.libraryHasSettings=(0,n.lazy)((()=>H())),t.libraryHasSettings.unset=()=>{V().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",G),(0,E.ee)().on("settingsChanged",G),I.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=H;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await T.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function Z(e,i){if(null==e)return void V().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ne("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(r,i),V().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:n}),n){const t=await(0,N.readTomlFile_)(r),i=await(0,N.readTomlFile_)(e);(0,u.eql)(t,i)?(V().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(V().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function K(e=(0,A.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await Z(t,(0,I.persistedSystemSettings)()),t}function X(e){return Q(j(e))}async function Y(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=j(e);return V().info("writeLibrarySettings()",{file:i}),null!=i&&(await Z(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=V().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=V().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,N.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,h.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,n.lazy)((()=>P.version)),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return Z(x.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Y,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,n.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function ne(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,z.WrapComments))))}t.clearLibraryDirSetting=async function(){await B(),I.Settings.libraryDir.unset(),await K()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(x.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(j())?.unlink("trace")),(0,E.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ne("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ne("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...O.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...O.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ne("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ne("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,f.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,R.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ne((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,h.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class f extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=f},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),f=i(38049);function h(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?h((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>h(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,f.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(87748);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),f=i(75556),h=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),F=i(43414),L=i(69301),A=i(82590),N=i(63526),R=i(26352),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function V(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function j(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function B(e){return null!=e&&(0,h.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=V,t.capturedAtSrcFromStat=j,t.isCapturedAtJson=B;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:B(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,f.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);j(this.src)&&(t=Math.max(F.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,h.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return V(this.src)}get isInferred(){return!V(this.src)&&!j(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,f.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?F.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:F.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(F.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(F.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function H(e){if(F.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return B(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!F.Settings.usePathsToInferDates.valueOrDefault||!F.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:F.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,F.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,F.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,R.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,R.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(F.Settings.useStatToInferDates.valueOrDefault?r("stat",await H(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,F.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=H},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),f=i(89253),h=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),F=i(2023),L=i(55568),A=i(43414),N=i(13378),R=i(14889),z=i(91464),V=i(53719),j=i(59387),B=i(65642),W=i(27947),U=i(74873),q=i(45581),G=i(94435),H=i(63526),$=i(31195),J=i(92330),Z=i(71932),K=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),R.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,V.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,h.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function he(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,z.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const n=x.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,h.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,h.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,h.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,F.assignNullishFields)(a.original,(0,h.pick)(a,...(0,h.keys)(r))),(0,h.assignFields)(a,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,F.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,h.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,ne.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,h.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,h.assignFields)(s,l),(0,h.assignFields)(s.inferred,l)}const c=o?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,K.extractLensMakeModel)(s),f=await(0,B.extractCapturedAt)(e,s,o);if(null==f)return void se().info("No capturedAt for "+e);!o&&f.isInferred&&(s.inferred.capturedAt=f);const m=(0,G.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:f,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,h.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,h.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,h.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,h.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,h.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,N.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await he(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=he,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new f.MultiMap;for(const[r,s]of(0,h.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=x.PosixFile.for(t),r=(0,h.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await he(n)),A.Settings.overwriteOriginal.valueOrDefault||await fe(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,N.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,H.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,h.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,h.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),ae&&(n.__instance=(0,O.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),f=i(82798),h=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,f.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,f.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,h.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(f.toS),o=(0,u.values)(i).map(f.toS);if((0,r.includesAny)(a,o))continue;const l=(0,h.least)((0,u.keys)(t)),c=(0,h.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),f=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const h=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return h()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:f.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:f.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:f.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:f.ExtTypes.Video},{exts:c.SidecarFiletypes,type:f.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:f.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:f.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,f.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,f.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(f.ExtTypes.Sharp)||t.includes(f.ExtTypes.RawImage)?"image":t.includes(f.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,f.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,f.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,f.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,f.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,f.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=f.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),f=i(84253),h=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,f.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,h.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,T._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const f=M.PosixFile.for(e);return await(0,T.overwriteTags_)(f,c),f.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=O(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,n){const r=x(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),F(i,r,s)},t.ensureHistoryRecords=F},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),f=i(64455),h=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,h.validLat)(t)||!(0,h.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,f.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),f=i(13779),h=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,f.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,h.validLat)(e)?e:void 0)),GPSLongitude:(0,f.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,h.validLon)(e)?e:void 0)),GPSAltitude:(0,f.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),f=i(43414),h=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,h.make)(e.LensMake),i=(0,h.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...f.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function f(e,t,i=""){const n=e.replace(t,i);return n===e?e:f(n,t,i)}const h=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=h.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=f(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=f(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function f(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function h(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=f,t.normalizeMimetype=h,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&h(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&h(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(f(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),f=i(63526);function h(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(h(m,p,{ignoreCase:l}))return!0;if(h(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),h(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,f.stripExt)(m),(0,f.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,f.stripExt)(p),(0,f.stripExt)(i.name)]))if(h((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(n.length)),l=s(i.slice(n.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),f=i(53026),h=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,f.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,h.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),f=i(13779),h=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),F=i(96593),L=i(17310),A=i(54988),N=i(27446),R=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),z=7;async function V(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(R().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(R().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(R().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,h.definedAndNotEql)(n.Make,i.Make))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,h.definedAndNotEql)(n.Model,i.Model))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return R().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await V(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const B=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return B().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,f.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7){if(!await V(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,N.isAssetFileMimeType)(e))))}));if(null==i)return void R().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,o.sortBy)(i,(e=>(0,O.bname)(e))),r=(0,x.findFileIndex)(e,n);if(r<0)return void R().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return R().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await V(e.parent()))return;const t=q(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,z);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return R().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}R().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return R().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void R().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return R().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return R().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}R().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return R().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return R().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),f=i(46573),h=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,f.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),h.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return h.URI.isUri(e)?e:h.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??h.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),f=i(51053),h=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!h.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(f.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=f.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=f.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,f.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const f=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function h(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&h(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return f().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||h(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),f=i(47044);function h(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,f.volsha)(t.uuid),path:u})},t.joinMountpoint=h,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,f.volsha)(i.uuid)===e.authority)return h(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?h(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?h(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),f=i(76531),h=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,h.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,f.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),f=i(7903),h=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,f.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,f.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,h.isGioSupported)())for(const e of(0,s.toA)(await(0,h.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),f=i(53719),h=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void h().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};h().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return h().warn("empty output",{localsOnly:e,paths:t}),[];h().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),f=i(39784),h=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,h.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,h.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,h.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,f.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(I)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),f=i(14889),h=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,h.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,h.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,h.stripPrefix)(e,"/"))).flatMap((e=>(0,h.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function f(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&f(u)})),u},t.setupVolumeTTL=f},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),f=i(28649),h=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,h.splitLines)(e).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),f=i(46852),h=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,f.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,h.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),f=i(55568),h=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,f.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{T.Settings.libraryDir.watchLater(L),T.Settings.scanPaths.watchLater(L),(0,f.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await z()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),h.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),N()),minCallDelayMs:h.ShortCommandTimeoutMs})})));const z=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:h.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),f=i(86472),h=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const n=await(0,h.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new f.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),f=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function h(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(h(),o.ShortCommandTimeoutMs)}catch(e){return f().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=h;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const f=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,h=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===f?.test(e)?"LinuxDevMapperRE":!0===h?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),f=i(9288),h=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>E())),(t=>{const i=(0,h.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,f.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),f=i(91464),h=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,f.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,h.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),f=i(43947),h=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),z=i(3955),V=i(98250),j=i(95725),B=i(76531),W=i(18501),U=i(58659),q=i(15203),G=i(51053),H=i(43414),$=i(47044),J=i(69329),Z=i(69551),K=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([V.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),V.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await fe(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),fe.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const fe=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function he(e){if(null==e)return;const i=new h.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:fe}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,z.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await fe()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,f.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(G.isWin?(0,Z.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,B.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(G.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(G.isWin?t:G.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await he(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>G.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,z.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:fe},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await fe())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),f=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function h(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=h,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,h());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),f().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){f().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else f().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(h(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),f=3;function h(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),f=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return f().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return f().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),f=i(43649),h=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),h.Settings.cpuBusyPercent.watchLater(v),h.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||h.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.floor((0,f.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),f=i(69547),h=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){h.maxCpus.refresh(),h.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,f.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{h.maxCpus.unset(),h.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),f=i(39784),h=i(82798);function m(e){return null!=e&&(0,f.toA)(e).length>0}function p(e){return null==e||0===(0,f.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,f.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,f.toA)(e).map((e=>(0,h.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(h(e,t),e)}function f(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return h(i.values(),t)}function h(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=f,t.sortUniq=function(e){return f(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(f(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=h,t.deepSortBy=function e(t,i){return h(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),f=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function h(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?f().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=h,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=h(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,h=s(e,t,u);if(null!==h)return h;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(f(e),f(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of o){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const f=/shortStack|errorToVerbose/;function h(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return h(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==f.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=h,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function f(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=f,t.groupByValues=function(e,t){const i=f(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function f(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=f;const h=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return f(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function f(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function h(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!h(e)}function p(e){return f(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??f(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(f(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,f)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of f(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=f,t.keysWithDefinedValues=function(e){return null==e?[]:f(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=h,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of f(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=f(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of f(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let f;function h(){if(void 0===f)try{f=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{f=null}return f??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=h();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=h();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=h();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),a=i(21669);async function o(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await o(e,i,r);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,s.tot)(n):a}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],f=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function h(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return h(e*t.MB,i)},t.fmtBytes=h,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=f[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(47065),module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),f=i(8199),h=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,f.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,f.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,h.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,h.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,h.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,f.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,h.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,h.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,h.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),f=i(92661),h=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,h.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,f.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),f.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(4866),r=i(9678),s=i(15203),a=i(51053);t.EditionType=(0,n.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),f=i(82798),h=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new h.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,f.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class f{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const h=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new f(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(h().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),f=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==f)this.skippedHeaders.push(m),h().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:f});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=f}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function f(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return f(e?.lat,e?.lon,t)},t.geohash=f,t.geohashNumericShort=function(e,t){return m(e,t,30)};const h=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?h.zip([t,e],l(i)):void 0}function p(e,t=o){return h.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),f=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),h={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{f(),(0,a.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,h,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new f(e,t)};class f extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),f=i(29405),h=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,f.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,h.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),f=i(10347),h=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,h.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,f.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function f(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function h(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=f,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=h,t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),f=i(13779),h=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,f.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,h.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),f=i(13779),h=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,h.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,a.lazy)((()=>(0,f.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),f=i(75556),h=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),F=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,f.gt0)(i)&&(0,f.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,f.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,f.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,f.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,f.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,f.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),a.push(R(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,f.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,h.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,f.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,f.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=z,z.instance=(0,o.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new z(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return z.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>z.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),z.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,o.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,f.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,h.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,h.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,f,h=!1,m=0;t=Math.ceil(t);const p=[];function g(){return h||m>Date.now()}function y(){if(null!=f){const e=f;f=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return f=r,(0,n.delay)(1).then((()=>e))}return async function(...n){h=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){h=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{f=void 0},v.donePromise=()=>{if(!h)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(f=void 0,h&&await v.donePromise(),h=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:h,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),f=i(44726),h=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,f.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(h.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!h()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||f(e)},t.isMainService=d,t.isWebService=f,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=h,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||f()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=n.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let o;const l=async i=>{const n=Date.now(),r=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function f(e,t){return h({obj:e,ready:t,stream:r.default.stdout})}function h({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=f,t.stderrWrite=function(e){return h({obj:e,stream:r.default.stdout})},t.writeTTY=h,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);f(t)},t.stdoutWriteMigration=function(e){return f({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>f({shutdownSync:!0}),restartSync:()=>f({restartSync:!0}),forceRestartSync:()=>f({forceRestartSync:!0}),rebuildLibrary:()=>f({rebuildLibrary:!0}),shutdown:()=>f({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),f=i(82798),h=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,f.toS)(e),t=(0,f.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,f.toS)(e).indexOf((0,f.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(f.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,f.toS)(e),t=(0,f.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,f.toS)(e),r=(0,f.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,f.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,f.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,f.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,f.toS)(e))},t.capitalize=function(e){return e=(0,f.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,h.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,f.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,f.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,h.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,f.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,f.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,f.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(f.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),f=i(2023),h=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,f.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,h.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const h=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){f(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),f(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,h.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const f=/^[\da-z]{9}-[\da-z]{7}$/i;function h(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return f.test((0,a.toS)(e))},t.tsFromUid=h,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>h(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),f=i(14889),h=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,h.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:f.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,f,h]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,f,h/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),f.set(this,void 0),h.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,h,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,h=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,f,"f")&&(v.default.clearTimeout(p(this,f,"f")),g(this,f,void 0,"f")),(0,M.gt0)(e)&&(g(this,f,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,f,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,o,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,o,"f")===T.PromiseStates.pending){(0,P.map)(p(this,f,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),f=i(91641),h=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return f.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,h.setEnding)(!0),w();for(const t of f.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of f.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),f=i(66776),h=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,h.toInt)(e)??0,t=(0,h.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const f=()=>{u(this,n,"a",l)&&(0,h.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,h.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),f())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):f(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,f.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,f.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),f=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,f.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),f=i(43414),h=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{f.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,h.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,o,"f")}unset(){f(this,s,0,"f"),f(this,r,void 0,"f"),f(this,a,void 0,"f"),f(this,o,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===n&&f(this,a,i,"f"),d(this,o,"f")?.id===n&&!(0,h.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{f(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){f(this,r,Date.now(),"f");const t=d(this,o,"f");return f(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),f=i(90957),h=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,f=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(f).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,f.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,h.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),f=i(94383),h=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new f.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new h.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const h=f(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new h.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let f=!1;const h=null==t?void 0:t+Date.now();let m=1;for(;null==h||Date.now()t/2&&!f&&(f=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return f||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),f=i(79015),h=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,o.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,f.ee)().on("clearCache",e),(0,f.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,h.childProcLocale)():{},...T(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),f=i(75556),h=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,h.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const a=new Date,o=[];return(0,b.niceable)(i,n)&&o.push((0,_.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,f.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&I(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,f.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,h.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,f.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,f.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(a.stdin);const S=new d.Latch;null==a.stdout?S.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==a.stderr||r?b.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),f=i(4866),h=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,h.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,f.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,h.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function f(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(f(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return a.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=f},37980:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(7304),r=i(97742),s=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),f=i(51053),h=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,h.addFooter)(n.program.description((0,m.cliWrap)(h.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:f.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const n=i(43414),r=i(66776),s=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,s.isEnvTrue)("NO_COLOR")&&(n.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>n.Settings.logColor.envValue=e))}}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,a.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),f=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function h(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=h,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?h(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),f=["year","month","day","hour","minute","second","millisecond"];class h{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:h.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new h(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=f.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new h(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=h},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),f=i(44726),h=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,h.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,f.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=T(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function O(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const f=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),h=(0,o.lt0)(f[0])?[f[0],...f.slice(1).map((e=>-e))]:f;return(0,c.sum)(h)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),f=i(1058),h=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:f,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!h.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==f))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:f??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,f.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,f.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),f=i(80294),h=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,f.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=h.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(h.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),f=i(65113),h=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,f.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${T(s)}:${T(a)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function F(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(F(e,t),l.dayMs)},t.diffMillis=F,t.closeTo=function(e,t,i){return(0,u.mapOr)(F(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(n+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(f.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,E.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),f=i(21040),h=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,h.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,f.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>I(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=F;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(N)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,h.toInt)(t.year),month:(0,h.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,h.toInt)(t.day)})}}const N=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),f=i(93125),h=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):h.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),a=i(36218),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),f=i(82798),h=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,h.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,f.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),f=i(70283),h=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,h.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,f.within)(k(),C(),e)}function F(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,f.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||F(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=F,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),f=i(70283),h=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,f.mapGte0)((0,h.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,o.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[a.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function f(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:f(),desc:"config"})},t.desktopConfigDirs=f},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),a=i(43414);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),f=i(43414),h=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,h.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,h.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,h.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,h.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(f.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),f=i(15203),h=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,f.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:h.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),f=i(83486),h=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,f.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,h.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),f=i(29405),h=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(h.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=m,(0,l.later)((()=>{f.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),f=i(24945),h=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,h.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new f.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function f(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=f;const h=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!h.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(f(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),f=i(53525),h=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,h.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const f=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===f?"error":"warn","onError()",{event:f,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+f.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),f=i(91464),h=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,f.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,f.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,h.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,f.dedupeNeedle)(i,n,"file")),(0,h.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,f.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),f=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(f.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function a(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),z=i(70283),V=i(55568),j=i(14889),B=i(45113),W=i(3917),U=i(31329),q=i(37086),G=i(34996),H=i(36079),$=i(91641),J=i(95557),Z=i(17354),K=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),fe=i(79015),he=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,B.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,fe.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,V.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,Z.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,z.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),E.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",h).call(this,e));r&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",f).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,V.isSyncService)()?(0,he.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new G.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,V.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,K.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:j.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},f=function(e){if(!(0,V.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,he.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,he.setIsSyncing)(!1)},h=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,V.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,H.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,V.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),f=(0,a.lazy)((()=>s.default.getgroups?.()));function h(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?h(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?h(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:f()??[],l=0===a,u=l||e.uid===a,h=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(h?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(h?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(h?8:0)|1)&e.mode)))}t.canAccessSync=h,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),f=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,f.resolve)(...e)}};const h=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,f.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:h().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,f.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=h(i(49411)),v=h(i(97742)),w=i(76402),S=h(i(47261)),b=h(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),z=i(13779),V=i(34996),j=i(46852),B=i(7383),W=i(21142),U=i(83486),q=i(49379),G=i(79015),H=i(79378),$=i(7162),J=i(6667),Z=i(51053),K=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),fe=i(35008),he=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,he.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,j.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,z.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,he.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,fe.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),f(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,K.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,j.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,j.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,j.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,he.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,B.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&f(this,a,void 0,"f"),f(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&f(this,a,void 0,"f"),f(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,j.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,j.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,j.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,j.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,j.thenMap)(this.statTimes(),z.max)}maxStatDate(){return(0,j.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,j.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,j.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,j.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,j.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,j.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,j.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,j.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,j.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,j.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,j.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,j.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,H.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,H.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,j.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,j.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,K.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,B.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new V.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,j.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new V.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,K.equalsIgnoreCase)(e.basename,this.base))),t=(0,z.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),a=i(3955);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const f=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function h(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return f().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return h((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=h,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),f=i(3955),h=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,h.toNativePath_)(e);await(0,f.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),f=i(39784),h=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,h.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,f.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,f.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),f=i(79015),h=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends h.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,f.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,f.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function f(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function h(e,...t){return e=f(e),t.some((t=>f(t)===e))}t.normalizeExt=f,t.isExt=h,t.isJpegExt=function(e){return h(e,...u.JpegExts)},t.isJsonExt=function(e){return h(e,"json")},t.isCsvExt=function(e){return h(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return h(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),f=i(98250),h=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,h.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(f.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,a,o,l,u,c,d,f,h,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),z=i(91641),V=i(95557),j=i(4691),B=i(17354),W=i(53525),U=i(9483),q=i(6231),G=i(53719),H=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(H.PsLockExt)+"$");class Z extends V.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??z.EndableRanks.postdb,(0,G.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),f.set(this,Date.now()),this.tryAcquire_=(0,B.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,H.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,H.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",h).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,j.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=Z,r=Z,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,n=new WeakSet,h=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,f,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,f,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,H.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},Z.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new Z(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),a=i(95725);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const f=d(i(44470)),h=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&h.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=h.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",o).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",o).call(this):!a&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(){const e=await(0,b.thenOrTimeout)(f.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function f(e,t={aggressive:!0}){return h((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function h(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:h(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=f(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=f,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=f(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),a=i(76402),o=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),f=i(24588),h=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,h.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,f.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(f.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),f=i(98462),h=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new h.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,f=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function h(e){return null!=f?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":h(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=h,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),f=i(94488),h=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new h.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===f.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,f.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const n=await Promise.race([E(e,t),x(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,f.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===f.CACHEDIR_TAG&&await(0,f.isCachedirTagFile)((0,a.join)(e,n.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,f.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),f=i(13779),h=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,h.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),f=i(82798),h=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,h.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,f.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),f=c(i(87561)),h=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),z=i(69317),V=i(14195),j=i(53525),B=i(49379),W=i(9483),U=i(6231),q=i(51053),G=i(49586),H=i(71663),$=i(43414),J=i(78362),Z=i(3874),K=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),fe=i(76333),he=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,Z.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>K.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,z.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,Z.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,V.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,V.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),K.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,fe.WipPrefix))}isWip(){return this.name.startsWith(fe.WipPrefix)}async wipIsRecent(e=fe.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,fe.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,B.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,he.zpipe_)(this.nativePath,f.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await h.default.copyFile(this.nativePath,n.nativePath,f.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await H.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,H.pwshQuote)(this.nativePath)} -Destination ${(0,H.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,z.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,z.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),f=i(40786),h=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,f.hasChildrenSync)(t,e))return t;for(const i of(0,f.ancestors)(t).slice(0,4)){if((0,f.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,f.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,h.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),f=i(20636),h=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=T(e),r=await(0,f.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===f.Timeout&&(0,p.onTimeout)({soft:!1}),r!==f.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new h.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),f=i(13594);function h(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:h(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=h,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return h(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(h(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,f.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function f(e){return null==e||e.isFile()&&0===e.size}function h(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:f(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=f,t.isDirectorySync=h,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(h(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class f extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=f,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),f=i(9288),h=i(27175);function m(){return(0,a.map)(h.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,f.pathIfExists)(m()?.join("bin",e))),(()=>(0,f.pathIfExists)(m()?.join(e))),(()=>(0,f.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,f.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),f=i(95725),h=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,f.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,f.dirname)(t.file));const o=(0,s.lazy)((()=>(0,h.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),f=i(39784),h=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,h.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,f.toA)(e))try{null!=i&&await o.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function f(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=f,t.writeTextSync_=function(e,...t){return f(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),f=i(7162),h=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,f.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new h.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),f=i(95487),h=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,f.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,h.hasPacman)()&&(i=(await(0,h.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),f=i(43414),h=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:f.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,h.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(f.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),f=i(10742),h=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,h.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{h.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,f.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),f=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),h=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return h().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?f().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):f().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>h.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?h.prior()?.clear():h.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{f().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:f().test(t)||!d().test(t),meta:{err:e,allow:f().test(t),block:d().test(t),validationErrorAllowlist:f().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),f=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>f.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),f=i(19658),h=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),F=i(68107),L=i(53719),A=i(7218),N=i(49441),R=i(12737),z=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function j(e){return f.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,R.ffmpegVersion_)()}function B(e,i){const n=V("extractMaxBitrate",e),r=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,h.mapGt0)(s,(e=>(0,h.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=j,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await j())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,R.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,N.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,F.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),f=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=f&&(null==c||f.height===c.height&&f.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:f}),r.nativePath;const h=(0,k.extractDurationSec)(l),m=Math.min(h??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:h}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,R.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,R.isFFmpegSupported)()}async function H(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,O.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=H;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await G())return;const n=V("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await H(e))return void n.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...B(e,d)},s=J(o,r.videoBitrateKbps,i),a=x.Settings.transcodeMaxDim.valueOrDefault,f=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(f,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const a=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,R.ffmpegTranscode_)(r));0!==o.code&&n.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,R.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),f=i(70283),h=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,h.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,f.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...F(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,a.maxCpus)()/4))))},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),f=i(95976),h=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,h.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,f.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),f=i(4691),h=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,f.ending)()||!0===e?.aborted){const t=(0,f.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,h.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),f=i(55568),h=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,f.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>f.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,h.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),f=i(75556),h=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,f.toInt)(t);return(0,o.blank)(e)||!(0,f.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),h.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,f=4){if(null==i)return null;if(f<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,f-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,f-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),f-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,f-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),f=i(65628),h=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(n.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),r.set(this,!1),s.set(this,!1),a.set(this,!1),this.from=(0,h.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,f.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,f.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,n,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,r,!0,"f")})),this.stream.on("end",(()=>{u(this,r,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,r,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,r,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,n,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,n,"m",l).call(this),t}},r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(e){if(null===e)u(this,r,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),f=i(8199),h=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),F=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,h.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,f.gte)(n,i))return;await(0,h.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const f=d(i(87561)),h=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),F=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,I.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,h.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=f.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),f=i(29405),h=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,h.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,f.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},47065:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Recent=void 0;const r=n(i(97742)),s=i(84492),a=i(11944),o=i(59694),l=i(88491),u=i(43947),c=i(1429),d=i(66776),f=i(75556),h=i(8199),m=i(7127),p=i(2126),g=i(46852),y=i(37980),v=i(64063),w=i(42885),S=i(98462),b=i(51081),P=i(57400),M=i(40374),_=i(94329),E=i(71951),T=i(77200),x=i(13755),D=i(53208),k=i(70283),C=i(43414),O=i(82041);let I;function F(e){r.default.stdout.write(e+b.Newline)}async function L(e){const t=S.BaseFile.for(e);if(await t.isFile())return[t.nativePath];if(await t.isDirectory()){const e=await t.descendants((e=>e.ext.startsWith(".log")));return e?.map((e=>e.nativePath))}}t.Recent={beforeParse:e=>e.option("--recent [duration]",'Automatically cat recent logs. The optional "duration" argument can either be a number, which will be interpreted in minutes, or an ISO 8601 duration string, like "1d" for 1 day, or "20m" for 20 minutes. Defaults to 1 day.'),afterParse:e=>{null!=e.recent&&(!0===e.recent?I=l.dayMs:(0,k.mapGt0)(e.recent,(e=>I=e*l.minuteMs))??(0,w.decodeDuration)(e.recent))}},async function(){const e=await new y.CLI(m.ServiceNames.logcat,"[FILE_OR_DIR...]","FILE_OR_DIR may be either a logfile or a directory that will be scanned for .log, .log.gz, and .log.bz files.").add(t.Recent,v.ColorArgs).parse();r.default.on("SIGINT",(()=>(0,p.exit)({reason:"SIGINT",status:0}))),r.default.on("SIGTERM",(()=>(0,p.exit)({reason:"SIGTERM",status:0})));const i=(0,a.uniq)((0,c.flatten)(await(0,g.mapAsync)({name:"parseArgs",arr:e.args,f:L})));if((0,f.gt0)(I)){const e=(0,M.matcherForExtOrCompressedExt)(".log");await(0,O.readSystemSettings)();const t=Date.now()-I;await S.BaseFile.for(C.Settings.logDir.valueOrDefault).visitDescendants((async n=>{const r=await n.maxStatMs();e(n.ext)&&await n.isFile()&&(0,h.gt)(r,t)&&i.push(n.nativePath)}))}const n=(0,E.DefaultLogFormatter)();if((0,a.isEmpty)(i))return(0,a.isNotEmpty)(e.args)&&(console.error(n.format("error","logcat","No valid logfiles were provided.")),e.help()),F(n.format("info","logcat","No log files provided: reading from stdin.")),F(n.format("warn","logcat","The output will not be sorted chronologically.")),void await s.promises.pipeline(r.default.stdin,new _.LineReader,new s.Transform({transform(e,t,i){(0,d.map)((0,D.chunkToLogEntry)(e),(e=>F(n.formatLogEntry({from:"",...e})))),i()}}));const l=await(0,g.thenCompact)(i.map((async e=>{const t=await P.DirectoryEntry.for(e);return null!=t&&(0,f.gt0)(t.size())?new x.LogReader(t,console.error):void 0})));function w(){let e;(0,a.filterInPlace)(l,(e=>!e.complete()));for(const t of l){if(!t.ready())return;const i=t.peek();null!=i?.ts&&(null==e||i.tse.f.nativePath))));l.length>0;)try{const e=w();if(null!=e)for(const t of e)F(n.formatLogEntry(t));else await(0,u.delay)(10,!1)}catch(e){console.error("caught error",e)}r.default.stdout.write(b.Newline,(()=>(0,p.exit)({reason:"",status:0})))}()},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),f=i(39784),h=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,h.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,f.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,f.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function f(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=f(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=f,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),f=i(8177),h=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new h.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,f.intersection)(e,t).size/(0,f.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),f=i(70283),h=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:h.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),f=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),f=i(53719),h=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return h().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(h().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class f extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=f},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),f=i(7162),h=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,f.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(h.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(4866),r=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),f=i(18226),h=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,n.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){T(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&x()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,f.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},E={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?E:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?h.ColorDistanceFunctions.cie76:h.ColorDistanceFunctions.ciede2000}function x(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=x},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),f=i(71756),h=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,h.tot)(this.optsOverrides.defaultValue)??(0,h.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,h.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,f.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,h.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,h.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,h.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),f=i(84253),h=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),z=i(98788),V=i(61659),j=i(40185),B=i(32994),W=i(39036),U=i(86115),q=i(36738),G=i(17679),H=i(75153),$=i(1440),J=i(92187),Z=i(79660),K=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),fe=i(39165),he=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new he.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new he.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new he.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new he.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new he.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new he.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new he.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new he.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new fe.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:G.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new he.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new K.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new Z.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new fe.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new he.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new he.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new he.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new he.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new he.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new he.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,H.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new he.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new he.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,H.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new fe.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,h.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new fe.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new K.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*h.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*h.GB}),validateJpegImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:j.NameTagFormats["as-is"],strEnum:j.NameTagFormats}),tagNamesDefaultFamily:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:B.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new he.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),f=i(82166),h=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,f.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(h.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),f=i(51367),h=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),E=i(79015),T=i(98462),x=i(98250),D=i(38846),k=i(23830),C=i(84161),O=i(44911),I=i(43414),F=i(95699),L=i(85560),A=i(98024),N=i(13060),R=i(31086),z=i(16704),V=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,M.libraryDataDirPosixFile)(e)?.join(L.SettingsToml)}async function B(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,N.readTomlFile_)((0,A.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function q(e){return(0,m.map)(j(e),(e=>J(e)))}function G(){t.libraryHasSettings.refresh()}function H(e){const t=j(e);return V().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await B(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=B,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Y()},t.libraryHasSettings=(0,n.lazy)((()=>H())),t.libraryHasSettings.unset=()=>{V().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",G),(0,E.ee)().on("settingsChanged",G),I.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=H;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await T.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function Z(e,i){if(null==e)return void V().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ne("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(r,i),V().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:n}),n){const t=await(0,N.readTomlFile_)(r),i=await(0,N.readTomlFile_)(e);(0,u.eql)(t,i)?(V().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(V().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function K(e=(0,A.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await Z(t,(0,I.persistedSystemSettings)()),t}function X(e){return Q(j(e))}async function Y(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=j(e);return V().info("writeLibrarySettings()",{file:i}),null!=i&&(await Z(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=V().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=V().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,N.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,h.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,n.lazy)((()=>P.version)),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return Z(x.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Y,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,n.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function ne(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,z.WrapComments))))}t.clearLibraryDirSetting=async function(){await B(),I.Settings.libraryDir.unset(),await K()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(x.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(j())?.unlink("trace")),(0,E.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ne("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ne("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...O.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...O.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ne("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ne("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,f.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,R.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ne((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,h.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class f extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=f},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),f=i(38049);function h(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?h((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>h(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,f.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(87748);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),f=i(75556),h=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),F=i(43414),L=i(69301),A=i(82590),N=i(63526),R=i(26352),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function V(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function j(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function B(e){return null!=e&&(0,h.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=V,t.capturedAtSrcFromStat=j,t.isCapturedAtJson=B;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:B(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,f.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);j(this.src)&&(t=Math.max(F.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,h.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return V(this.src)}get isInferred(){return!V(this.src)&&!j(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,f.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?F.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:F.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(F.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(F.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function H(e){if(F.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return B(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!F.Settings.usePathsToInferDates.valueOrDefault||!F.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:F.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,F.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,F.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,R.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,R.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(F.Settings.useStatToInferDates.valueOrDefault?r("stat",await H(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,F.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=H},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),f=i(89253),h=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),F=i(2023),L=i(55568),A=i(43414),N=i(13378),R=i(14889),z=i(91464),V=i(53719),j=i(59387),B=i(65642),W=i(27947),U=i(74873),q=i(45581),G=i(94435),H=i(63526),$=i(31195),J=i(92330),Z=i(71932),K=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),R.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,V.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,h.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function he(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,z.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const n=x.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,h.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,h.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,h.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,F.assignNullishFields)(a.original,(0,h.pick)(a,...(0,h.keys)(r))),(0,h.assignFields)(a,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,F.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,h.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,ne.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,h.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,h.assignFields)(s,l),(0,h.assignFields)(s.inferred,l)}const c=o?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,K.extractLensMakeModel)(s),f=await(0,B.extractCapturedAt)(e,s,o);if(null==f)return void se().info("No capturedAt for "+e);!o&&f.isInferred&&(s.inferred.capturedAt=f);const m=(0,G.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:f,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,h.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,h.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,h.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,h.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,h.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,N.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await he(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=he,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new f.MultiMap;for(const[r,s]of(0,h.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=x.PosixFile.for(t),r=(0,h.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await he(n)),A.Settings.overwriteOriginal.valueOrDefault||await fe(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,N.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,H.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,h.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,h.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),ae&&(n.__instance=(0,O.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),f=i(82798),h=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,f.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,f.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,h.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(f.toS),o=(0,u.values)(i).map(f.toS);if((0,r.includesAny)(a,o))continue;const l=(0,h.least)((0,u.keys)(t)),c=(0,h.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),f=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const h=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return h()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:f.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:f.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:f.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:f.ExtTypes.Video},{exts:c.SidecarFiletypes,type:f.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:f.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:f.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,f.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,f.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(f.ExtTypes.Sharp)||t.includes(f.ExtTypes.RawImage)?"image":t.includes(f.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,f.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,f.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,f.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,f.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,f.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=f.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),f=i(84253),h=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,f.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,h.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,T._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const f=M.PosixFile.for(e);return await(0,T.overwriteTags_)(f,c),f.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=O(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,n){const r=x(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),F(i,r,s)},t.ensureHistoryRecords=F},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),f=i(64455),h=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,h.validLat)(t)||!(0,h.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,f.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),f=i(13779),h=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,f.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,h.validLat)(e)?e:void 0)),GPSLongitude:(0,f.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,h.validLon)(e)?e:void 0)),GPSAltitude:(0,f.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),f=i(43414),h=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,h.make)(e.LensMake),i=(0,h.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...f.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function f(e,t,i=""){const n=e.replace(t,i);return n===e?e:f(n,t,i)}const h=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=h.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=f(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=f(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function f(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function h(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=f,t.normalizeMimetype=h,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&h(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&h(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(f(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),f=i(63526);function h(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(h(m,p,{ignoreCase:l}))return!0;if(h(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),h(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,f.stripExt)(m),(0,f.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,f.stripExt)(p),(0,f.stripExt)(i.name)]))if(h((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(n.length)),l=s(i.slice(n.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),f=i(53026),h=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,f.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,h.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),f=i(13779),h=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),F=i(96593),L=i(17310),A=i(54988),N=i(27446),R=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),z=7;async function V(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(R().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(R().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(R().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,h.definedAndNotEql)(n.Make,i.Make))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,h.definedAndNotEql)(n.Model,i.Model))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return R().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await V(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const B=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return B().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,f.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7){if(!await V(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,N.isAssetFileMimeType)(e))))}));if(null==i)return void R().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,o.sortBy)(i,(e=>(0,O.bname)(e))),r=(0,x.findFileIndex)(e,n);if(r<0)return void R().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return R().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await V(e.parent()))return;const t=q(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,z);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return R().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}R().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return R().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void R().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return R().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return R().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}R().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return R().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return R().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),f=i(46573),h=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,f.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),h.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return h.URI.isUri(e)?e:h.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??h.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),f=i(51053),h=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!h.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(f.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=f.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=f.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,f.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const f=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function h(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&h(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return f().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||h(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),f=i(47044);function h(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,f.volsha)(t.uuid),path:u})},t.joinMountpoint=h,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,f.volsha)(i.uuid)===e.authority)return h(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?h(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?h(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),f=i(76531),h=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,h.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,f.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),f=i(7903),h=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,f.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,f.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,h.isGioSupported)())for(const e of(0,s.toA)(await(0,h.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),f=i(53719),h=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void h().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};h().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return h().warn("empty output",{localsOnly:e,paths:t}),[];h().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),f=i(39784),h=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,h.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,h.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,h.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,f.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(I)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),f=i(14889),h=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,h.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,h.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,h.stripPrefix)(e,"/"))).flatMap((e=>(0,h.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function f(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&f(u)})),u},t.setupVolumeTTL=f},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),f=i(28649),h=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,h.splitLines)(e).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),f=i(46852),h=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,f.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,h.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),f=i(55568),h=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,f.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{T.Settings.libraryDir.watchLater(L),T.Settings.scanPaths.watchLater(L),(0,f.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await z()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),h.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),N()),minCallDelayMs:h.ShortCommandTimeoutMs})})));const z=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:h.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),f=i(86472),h=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const n=await(0,h.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new f.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),f=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function h(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(h(),o.ShortCommandTimeoutMs)}catch(e){return f().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=h;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const f=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,h=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===f?.test(e)?"LinuxDevMapperRE":!0===h?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),f=i(9288),h=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>E())),(t=>{const i=(0,h.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,f.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),f=i(91464),h=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,f.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,h.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),f=i(43947),h=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),z=i(3955),V=i(98250),j=i(95725),B=i(76531),W=i(18501),U=i(58659),q=i(15203),G=i(51053),H=i(43414),$=i(47044),J=i(69329),Z=i(69551),K=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([V.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),V.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await fe(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),fe.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const fe=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function he(e){if(null==e)return;const i=new h.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:fe}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,z.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await fe()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,f.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(G.isWin?(0,Z.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,B.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(G.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(G.isWin?t:G.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await he(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>G.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,z.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:fe},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await fe())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),f=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function h(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=h,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,h());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),f().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){f().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else f().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(h(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),f=3;function h(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),f=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return f().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return f().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),f=i(43649),h=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),h.Settings.cpuBusyPercent.watchLater(v),h.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||h.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.floor((0,f.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),f=i(69547),h=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){h.maxCpus.refresh(),h.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,f.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{h.maxCpus.unset(),h.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),f=i(39784),h=i(82798);function m(e){return null!=e&&(0,f.toA)(e).length>0}function p(e){return null==e||0===(0,f.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,f.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,f.toA)(e).map((e=>(0,h.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(h(e,t),e)}function f(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return h(i.values(),t)}function h(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=f,t.sortUniq=function(e){return f(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(f(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=h,t.deepSortBy=function e(t,i){return h(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),f=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function h(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?f().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=h,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=h(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,h=s(e,t,u);if(null!==h)return h;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(f(e),f(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of o){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const f=/shortStack|errorToVerbose/;function h(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return h(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==f.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=h,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function f(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=f,t.groupByValues=function(e,t){const i=f(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function f(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=f;const h=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return f(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function f(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function h(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!h(e)}function p(e){return f(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??f(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(f(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,f)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of f(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=f,t.keysWithDefinedValues=function(e){return null==e?[]:f(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=h,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of f(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=f(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of f(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let f;function h(){if(void 0===f)try{f=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{f=null}return f??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=h();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=h();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=h();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),a=i(21669);async function o(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await o(e,i,r);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,s.tot)(n):a}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],f=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function h(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return h(e*t.MB,i)},t.fmtBytes=h,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=f[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(47065),module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/logtail.js b/bin/logtail.js index 0e77a00..c8b9737 100755 --- a/bin/logtail.js +++ b/bin/logtail.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*o.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(4866),r=i(9678),s=i(15203),o=i(51053);t.EditionType=(0,n.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var o=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),o=i(70283),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=a){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=a){return f.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),o=i(87748),a=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,o.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),o=i(61570),a=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,o.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),o=i(4866),a=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,o.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=z,z.instance=(0,a.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new z(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return z.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>z.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),z.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),o=i(19658),a=i(55568);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=n.ServiceNames.main);const t=a.serviceName.prior();t!==e&&(o.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),o=i(18991),a=i(43414);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...T(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,a.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(7304),r=i(97742),s=i(42041),o=i(39938),a=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(n.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,o.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,a.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const n=i(43414),r=i(66776),s=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,s.isEnvTrue)("NO_COLOR")&&(n.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>n.Settings.logColor.envValue=e))}}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),o=i(75556),a=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,o.toInt)(n.index),(0,o.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,o.clamp)(1,1e3,(0,o.toInt)(n,{defaultValue:1})),i=(0,o.clamp)(0,n-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new f(e,a,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(59694),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=T(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,o.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:o,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==o)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,a.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:o,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),o=i(21040),a=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,o.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,a.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),o=i(11944),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,a.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,a.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(o=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:o,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),o=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${T(s)}:${T(o)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,o.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function F(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(F(e,t),l.dayMs)},t.diffMillis=F,t.closeTo=function(e,t,i){return(0,u.mapOr)(F(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,o]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),a=(o-s)/(n+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+a*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,o.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,E.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>I(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=o(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=F;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,n,"m",s).call(this))),o(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(N)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),o(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),o(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const N=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(o(e))||(0,r.gt0)(a(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(a(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),o=i(66776),a=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),o=n(),l=(0,a.toGt0)(n()),u=(0,a.toGt0)(n()),c=(0,a.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),o=i(36218),a=(0,n.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,r.sort)([...a().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(11944),a=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,o.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,o.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),a.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getFullYear()),a.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getMonth()+1),a.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function F(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,h.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||F(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=F,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),o=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),z=i(70283),j=i(55568),V=i(14889),B=i(45113),W=i(3917),U=i(31329),q=i(37086),G=i(34996),H=i(36079),J=i(91641),$=i(95557),Z=i(17354),K=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,B.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,Z.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,z.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,k.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new G.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,K.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,H.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),z=i(13779),j=i(34996),V=i(46852),B=i(7383),W=i(21142),U=i(83486),q=i(49379),G=i(79015),H=i(79378),J=i(7162),$=i(6667),Z=i(51053),K=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,z.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,K.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,B.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),z.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,H.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,H.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,K.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,B.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,K.equalsIgnoreCase)(e.basename,this.base))),t=(0,z.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),o=i(3955);function a(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(r.ExtTypes.Video),t.isAssetFileExtension=a(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),o=i(7162),a=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(o)?void 0:{ext:o,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),z=i(91641),j=i(95557),V=i(4691),B=i(17354),W=i(53525),U=i(9483),q=i(6231),G=i(53719),H=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(H.PsLockExt)+"$");class Z extends j.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??z.EndableRanks.postdb,(0,G.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,B.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,H.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,H.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=Z,r=Z,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,H.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},Z.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new Z(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),o=i(76402),a=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const n=await Promise.race([E(e,t),x(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),z=i(69317),j=i(14195),V=i(53525),B=i(49379),W=i(9483),U=i(6231),q=i(51053),G=i(49586),H=i(71663),J=i(43414),$=i(78362),Z=i(3874),K=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,Z.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>K.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,z.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,Z.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),K.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,B.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await H.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,H.pwshQuote)(this.nativePath)} -Destination ${(0,H.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,z.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,z.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=T(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),o=i(66776),a=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,o.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const a=s(i(93977)),l=o(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await a.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),o=i(33714),a=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,a.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:o.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),o=i(46852),a=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),o=i(4866),a=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),o=i(43947),a=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),o=i(8199),a=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),o=i(7162),a=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,n.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,o]=e.split("\t"),a=(0,r.toGt0)(s),l=(0,r.toGt0)(o);return null==a||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),o=i(7162),a=i(43414),l=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:a.Settings.previewQuality.valueOrDefault,progressive:a.Settings.previewProgressive.valueOrDefault,mozjpeg:a.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),o=i(7162),a=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,a.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,a.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),o=i(88491),a=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),F=i(68107),L=i(53719),A=i(7218),N=i(49441),R=i(12737),z=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function V(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,R.ffmpegVersion_)()}function B(e,i){const n=j("extractMaxBitrate",e),r=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,r))return n.throw("invalid height: "+o,{ignorable:!0});const a=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=V,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await V())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,R.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,N.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const a=await n.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,F.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>a&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,R.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,R.isFFmpegSupported)()}async function H(e){const t=j("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,O.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,r.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=H;const J=new g.TTLMap(15*o.minuteMs);function $(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await G())return;const n=j("transcode",e),r=J.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const o=new y.Deferred(e.nativePath);if(J.set(t.nativePath,o),!1===await H(e))return void n.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...B(e,d)},s=$(a,r.videoBitrateKbps,i),o=x.Settings.transcodeMaxDim.valueOrDefault,h=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(o)&&(0,c.gt)(h,o)){const e=(0,l.fitInside)(d.dimensions,{width:o,height:o});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:o}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const o=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const a=await o.observe((0,R.ffmpegTranscode_)(r));0!==a.code&&n.throw("transcode failed with code "+a.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=$,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,R.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(88491),a=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...F(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),o=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,o.maxCpus)()/4))))},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),o=i(51053),a=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),o=i(39938),a=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(43947),a=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),o=i(4866),a=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?r(this,n,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),o=i(11944),a=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,o.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,a.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,a.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),o=i(44726),a=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(a));return(0,n.isNotEmpty)(c)&&(a["โ€ฆ"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),o=i(92332),a=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),F=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),F=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,I.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,n,"m",o).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",o).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),o=i(95998),a=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,r.splitLines)(a)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),o=i(24945),a=i(9483);t.SentLogLevels=(0,n.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),o=i(26302),a=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,o.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,a.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},66585:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(97742)),s=i(55248),o=i(11944),a=i(7127),l=i(37980),u=i(64063),c=i(35796);!async function(){const e=(0,c.logDir)(),t=await new l.CLI(a.ServiceNames.logtail,"[LOG_DIR]","Normally logtail watches all files in the default logging directory, "+e+". Specify LOG_DIR or set the PS_LOG_DIR environment variable to override this directory.").add(u.ColorArgs).parse();r.default.on("SIGINT",(()=>r.default.exit(0))),r.default.on("SIGTERM",(()=>r.default.exit(0)));const i=(0,o.compactBlanks)(t.args);new s.LogTail(i[0]??e)}()},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),o=i(39784),a=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),o=i(63410),a=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),z=i(98788),j=i(61659),V=i(40185),B=i(32994),W=i(39036),U=i(86115),q=i(36738),G=i(17679),H=i(75153),J=i(1440),$=i(92187),Z=i(79660),K=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:G.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new K.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new Z.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,H.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,H.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new K.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:B.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),F=i(43414),L=i(69301),A=i(82590),N=i(63526),R=i(26352),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function B(e){return null!=e&&(0,f.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=B;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:B(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);V(this.src)&&(t=Math.max(F.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?F.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:F.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),o=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:o}),o}function q(e,t){if(F.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(F.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function H(e){if(F.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return B(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!F.Settings.usePathsToInferDates.valueOrDefault||!F.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:F.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=r("tags",U(t,F.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,F.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,R.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,R.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(F.Settings.useStatToInferDates.valueOrDefault?r("stat",await H(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return U(e,F.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=H},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),o=i(96593),a=i(27446);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),F=i(2023),L=i(55568),A=i(43414),N=i(13378),R=i(14889),z=i(91464),j=i(53719),V=i(59387),B=i(65642),W=i(27947),U=i(74873),q=i(45581),G=i(94435),H=i(63526),J=i(31195),$=i(92330),Z=i(71932),K=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,a.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const ae=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,V.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=ae();return e.ended?ae.refresh():e}function ue(e=!1){return(0,d.map)(ae.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),R.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(ae.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,z.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||o||a;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function pe(e,i=!0){const n=x.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},a=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(n.History)),(0,F.assignNullishFields)(o.original,(0,f.pick)(o,...(0,f.keys)(r))),(0,f.assignFields)(o,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,J.getInferredHistoricValues)(a,e),(0,F.assignNullishFields)(o,o.inferred),o.Rotation=(0,Q.orientationToRotation)(o.Rotation),se().debug("readRawTags() final",{pf:n,inferred:o.inferred,pickedResult:(0,f.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,ne.canInferForDir)(e.parent()),l=await(0,$.maybeInferTimezone)(e,s,a);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=a?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,K.extractLensMakeModel)(s),h=await(0,B.extractCapturedAt)(e,s,a);if(null==h)return void se().info("No capturedAt for "+e);!a&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,N.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=x.PosixFile.for(t),r=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await fe(n)),A.Settings.overwriteOriginal.valueOrDefault||await he(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,N.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,H.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),oe&&(n.__instance=(0,O.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(87748),a=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,n=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[o])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}n.push([o,(0,l.gt0)(a)?a:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),o=r(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const o=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(h.toS),a=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(o,a))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),o=i(61570),a=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,n){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,T.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,o.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const n=O(e);(0,a.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,n){const r=x(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),F(i,r,s)},t.ensureHistoryRecords=F},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),o=i(4866),a=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,o.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,h.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),o=(0,d.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,d.normalizeZone)(o);if(null!=a)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),o=i(38625),a=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(66776),a=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),o=i(61570),a=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),o=i(71923),a=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,n.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function o(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),o=i(21084),a=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),o=i(57743),a=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,o.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),F=i(96593),L=i(17310),A=i(54988),N=i(27446),R=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),z=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(R().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(R().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(R().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function V(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return R().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const B=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return B().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await V(t?.younger),n=await V(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,o.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,N.isAssetFileMimeType)(e))))}));if(null==i)return void R().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,a.sortBy)(i,(e=>(0,O.bname)(e))),r=(0,x.findFileIndex)(e,n);if(r<0)return void R().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,o.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,o.isNotEmpty)(u)&&d.length=s&&d.push(t)}return R().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,z);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return R().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}R().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return R().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void R().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return R().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return R().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}R().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return R().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return R().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),o=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,o.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:M(a,!1)),n}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{T.Settings.libraryDir.watchLater(L),T.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await z()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const z=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),z=i(3955),j=i(98250),V=i(95725),B=i(76531),W=i(18501),U=i(58659),q=i(15203),G=i(51053),H=i(43414),J=i(47044),$=i(69329),Z=i(69551),K=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([j.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,z.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(G.isWin?(0,Z.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,B.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(G.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(G.isWin?t:G.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>G.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,z.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,r)}t.isChrome=l,t.isSafari=function(e){return a(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(66585),module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of x((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*o.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(4866),r=i(9678),s=i(15203),o=i(51053);t.EditionType=(0,n.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var o=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),o=i(70283),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=a){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=a){return f.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),o=i(87748),a=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,o.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),o=i(61570),a=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,o.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),o=i(4866),a=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,o.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=z,z.instance=(0,a.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new z(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return z.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>z.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),z.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),o=i(19658),a=i(55568);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=n.ServiceNames.main);const t=a.serviceName.prior();t!==e&&(o.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),o=i(18991),a=i(43414);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...T(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,a.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(7304),r=i(97742),s=i(42041),o=i(39938),a=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(n.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,o.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,a.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const n=i(43414),r=i(66776),s=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,s.isEnvTrue)("NO_COLOR")&&(n.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>n.Settings.logColor.envValue=e))}}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),o=i(75556),a=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,o.toInt)(n.index),(0,o.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,o.clamp)(1,1e3,(0,o.toInt)(n,{defaultValue:1})),i=(0,o.clamp)(0,n-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new f(e,a,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(59694),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=T(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,o.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:o,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==o)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,a.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:o,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),o=i(21040),a=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,o.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,a.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),o=i(11944),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,a.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,a.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(o=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:o,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),o=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${T(s)}:${T(o)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,o.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function F(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(F(e,t),l.dayMs)},t.diffMillis=F,t.closeTo=function(e,t,i){return(0,u.mapOr)(F(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,o]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),a=(o-s)/(n+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+a*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,o.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,E.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>I(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=o(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=F;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,n,"m",s).call(this))),o(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(N)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),o(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),o(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const N=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(o(e))||(0,r.gt0)(a(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(a(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),o=i(66776),a=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),o=n(),l=(0,a.toGt0)(n()),u=(0,a.toGt0)(n()),c=(0,a.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),o=i(36218),a=(0,n.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,r.sort)([...a().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(11944),a=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,o.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,o.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),a.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getFullYear()),a.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getMonth()+1),a.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function F(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,h.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||F(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=F,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),o=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),z=i(70283),j=i(55568),V=i(14889),B=i(45113),W=i(3917),U=i(31329),q=i(37086),G=i(34996),H=i(36079),J=i(91641),$=i(95557),Z=i(17354),K=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,B.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,Z.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,z.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,k.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new G.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,K.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,H.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),z=i(13779),j=i(34996),V=i(46852),B=i(7383),W=i(21142),U=i(83486),q=i(49379),G=i(79015),H=i(79378),J=i(7162),$=i(6667),Z=i(51053),K=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,z.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,K.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,B.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,B.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),z.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,H.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,H.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,K.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,B.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,K.equalsIgnoreCase)(e.basename,this.base))),t=(0,z.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),o=i(3955);function a(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(r.ExtTypes.Video),t.isAssetFileExtension=a(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),o=i(7162),a=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(o)?void 0:{ext:o,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),z=i(91641),j=i(95557),V=i(4691),B=i(17354),W=i(53525),U=i(9483),q=i(6231),G=i(53719),H=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(H.PsLockExt)+"$");class Z extends j.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??z.EndableRanks.postdb,(0,G.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,B.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,H.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,H.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=Z,r=Z,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,H.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},Z.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new Z(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),o=i(76402),a=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const n=await Promise.race([E(e,t),x(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),z=i(69317),j=i(14195),V=i(53525),B=i(49379),W=i(9483),U=i(6231),q=i(51053),G=i(49586),H=i(71663),J=i(43414),$=i(78362),Z=i(3874),K=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,Z.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>K.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,z.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,Z.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),K.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,B.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await H.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,H.pwshQuote)(this.nativePath)} -Destination ${(0,H.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,z.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,z.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=T(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),o=i(66776),a=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,o.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const a=s(i(93977)),l=o(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await a.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),o=i(33714),a=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,a.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:o.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),o=i(46852),a=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),o=i(4866),a=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),o=i(43947),a=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),o=i(8199),a=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),o=i(7162),a=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,n.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,o]=e.split("\t"),a=(0,r.toGt0)(s),l=(0,r.toGt0)(o);return null==a||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),o=i(7162),a=i(43414),l=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:a.Settings.previewQuality.valueOrDefault,progressive:a.Settings.previewProgressive.valueOrDefault,mozjpeg:a.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),o=i(7162),a=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,a.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,a.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),o=i(88491),a=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),F=i(68107),L=i(53719),A=i(7218),N=i(49441),R=i(12737),z=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function V(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,R.ffmpegVersion_)()}function B(e,i){const n=j("extractMaxBitrate",e),r=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,r))return n.throw("invalid height: "+o,{ignorable:!0});const a=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=V,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await V())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,R.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,N.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const a=await n.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,F.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>a&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,R.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,R.isFFmpegSupported)()}async function H(e){const t=j("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,O.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,r.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=H;const J=new g.TTLMap(15*o.minuteMs);function $(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await G())return;const n=j("transcode",e),r=J.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const o=new y.Deferred(e.nativePath);if(J.set(t.nativePath,o),!1===await H(e))return void n.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...B(e,d)},s=$(a,r.videoBitrateKbps,i),o=x.Settings.transcodeMaxDim.valueOrDefault,h=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(o)&&(0,c.gt)(h,o)){const e=(0,l.fitInside)(d.dimensions,{width:o,height:o});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:o}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const o=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const a=await o.observe((0,R.ffmpegTranscode_)(r));0!==a.code&&n.throw("transcode failed with code "+a.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=$,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,R.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(88491),a=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...F(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),o=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,o.maxCpus)()/4))))},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),o=i(51053),a=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),o=i(39938),a=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(43947),a=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),o=i(4866),a=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?r(this,n,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),o=i(11944),a=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,o.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,a.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,a.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),o=i(44726),a=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(a));return(0,n.isNotEmpty)(c)&&(a["โ€ฆ"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),o=i(92332),a=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),F=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),F=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,I.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,n,"m",o).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",o).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),o=i(95998),a=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,r.splitLines)(a)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),o=i(24945),a=i(9483);t.SentLogLevels=(0,n.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),o=i(26302),a=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,o.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,a.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},66585:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(97742)),s=i(55248),o=i(11944),a=i(7127),l=i(37980),u=i(64063),c=i(35796);!async function(){const e=(0,c.logDir)(),t=await new l.CLI(a.ServiceNames.logtail,"[LOG_DIR]","Normally logtail watches all files in the default logging directory, "+e+". Specify LOG_DIR or set the PS_LOG_DIR environment variable to override this directory.").add(u.ColorArgs).parse();r.default.on("SIGINT",(()=>r.default.exit(0))),r.default.on("SIGTERM",(()=>r.default.exit(0)));const i=(0,o.compactBlanks)(t.args);new s.LogTail(i[0]??e)}()},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),o=i(39784),a=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),o=i(63410),a=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),z=i(98788),j=i(61659),V=i(40185),B=i(32994),W=i(39036),U=i(86115),q=i(36738),G=i(17679),H=i(75153),J=i(1440),$=i(92187),Z=i(79660),K=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new Z.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:G.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new K.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new Z.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new Z.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,H.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,H.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new K.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:B.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),F=i(43414),L=i(69301),A=i(82590),N=i(63526),R=i(26352),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function B(e){return null!=e&&(0,f.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=B;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:B(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);V(this.src)&&(t=Math.max(F.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?F.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:F.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),o=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:o}),o}function q(e,t){if(F.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(F.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function H(e){if(F.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return B(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!F.Settings.usePathsToInferDates.valueOrDefault||!F.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:F.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=r("tags",U(t,F.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,F.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,R.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,R.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,R.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(F.Settings.useStatToInferDates.valueOrDefault?r("stat",await H(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return U(e,F.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=H},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),o=i(96593),a=i(27446);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),F=i(2023),L=i(55568),A=i(43414),N=i(13378),R=i(14889),z=i(91464),j=i(53719),V=i(59387),B=i(65642),W=i(27947),U=i(74873),q=i(45581),G=i(94435),H=i(63526),J=i(31195),$=i(92330),Z=i(71932),K=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,a.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const ae=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,V.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=ae();return e.ended?ae.refresh():e}function ue(e=!1){return(0,d.map)(ae.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),R.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(ae.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,z.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||o||a;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function pe(e,i=!0){const n=x.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},a=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(n.History)),(0,F.assignNullishFields)(o.original,(0,f.pick)(o,...(0,f.keys)(r))),(0,f.assignFields)(o,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,J.getInferredHistoricValues)(a,e),(0,F.assignNullishFields)(o,o.inferred),o.Rotation=(0,Q.orientationToRotation)(o.Rotation),se().debug("readRawTags() final",{pf:n,inferred:o.inferred,pickedResult:(0,f.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,ne.canInferForDir)(e.parent()),l=await(0,$.maybeInferTimezone)(e,s,a);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=a?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,K.extractLensMakeModel)(s),h=await(0,B.extractCapturedAt)(e,s,a);if(null==h)return void se().info("No capturedAt for "+e);!a&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,N.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=x.PosixFile.for(t),r=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await fe(n)),A.Settings.overwriteOriginal.valueOrDefault||await he(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,N.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,H.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),oe&&(n.__instance=(0,O.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(87748),a=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,n=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[o])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}n.push([o,(0,l.gt0)(a)?a:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),o=r(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const o=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(h.toS),a=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(o,a))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),o=i(61570),a=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,n){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,T.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,o.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const n=O(e);(0,a.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,n){const r=x(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),F(i,r,s)},t.ensureHistoryRecords=F},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),o=i(4866),a=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,o.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,h.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),o=(0,d.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,d.normalizeZone)(o);if(null!=a)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),o=i(38625),a=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(66776),a=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),o=i(61570),a=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),o=i(71923),a=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,n.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function o(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),o=i(21084),a=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),o=i(57743),a=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,o.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),F=i(96593),L=i(17310),A=i(54988),N=i(27446),R=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),z=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(R().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(R().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(R().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function V(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))R().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return R().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const B=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return B().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await V(t?.younger),n=await V(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,o.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,N.isAssetFileMimeType)(e))))}));if(null==i)return void R().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,a.sortBy)(i,(e=>(0,O.bname)(e))),r=(0,x.findFileIndex)(e,n);if(r<0)return void R().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,o.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,o.isNotEmpty)(u)&&d.length=s&&d.push(t)}return R().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,z);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return R().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}R().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return R().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void R().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return R().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return R().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}R().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return R().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return R().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),o=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,o.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:M(a,!1)),n}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{T.Settings.libraryDir.watchLater(L),T.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await z()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const z=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),z=i(3955),j=i(98250),V=i(95725),B=i(76531),W=i(18501),U=i(58659),q=i(15203),G=i(51053),H=i(43414),J=i(47044),$=i(69329),Z=i(69551),K=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([j.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,z.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(G.isWin?(0,Z.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,B.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(G.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(G.isWin?t:G.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>G.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,z.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,r)}t.isChrome=l,t.isSafari=function(e){return a(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(66585),module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/main.js b/bin/main.js index cef9fd4..83e2002 100755 --- a/bin/main.js +++ b/bin/main.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(74485),{decode:s}=i(87536),o=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:a,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==a&&"public"!==a)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:a};if("local"===a)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=s(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?o(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:o,notBefore:a,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(a))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.kid must be a string");c.kid=o}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),n=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:o,issuer:a,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.issuer must be a string");if(d.iss!==a)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.subject must be a string");if(d.sub!==o)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),n=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:n}=i(74485),s=i(88277),{decode:o}=i(87536),a=i(91225);e.exports={post:function(e,t,i,r,n,o,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:o?.length?o:void 0,version:e,purpose:l}:n}const u=a(n);return s(i,u),r?{payload:u,footer:o?.length?o:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:a}=t.slice(e.length).split(".");try{r(a<=2),i=o(i),s=o(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},45112:(e,t,i)=>{const r=i(6113),n=i(16464),s=i(97540),o=i(45018),{PasetoDecryptionFailed:a}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",a=m(e,r.randomBytes(32)).subarray(0,32),l=a.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,a.subarray(16)),y=s(n,a,p,t),v=m(y,f);return o(n,t,a,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),o=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=s("v1.local.",r,o,t),v=m(g,p);if(!l(n,v))throw new a("decryption failed");const w=await y(o,f,r.subarray(16));if(!w)throw new a("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const a="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),S=s(a,l,w,t,n),b=m(S,p);return o(a,t,l,w,b)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),o=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),S=s("v3.local.",n,u,t,r),b=m(S,g);if(!l(o,b))throw new a("decryption failed");const P=await y(u,v,w);if(!P)throw new a("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:n}=i(35740);n||(n=e=>null!=e&&e instanceof r),e.exports=n},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const n=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(n*t);case"day":case"days":case"d":return Math.round(864e5*n);case"week":case"weeks":case"w":return Math.round(6048e5*n);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*n)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:n}=i(39084),s=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),n=i(97540),s=i(45018);e.exports=async function(e,t,i,o,a,l,u){const c=n(u,e,t,i,l),d=await r(o,c,a);return s(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),n=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:n}=i(45112),s=i(97540),{pre:o}=i(97362);e.exports=async function(e,t,i,a,l,u,c){const{raw:d,f:h}=o(e,t),f=d.subarray(0,-a),m=d.subarray(-a),p=s(c,e,f,h,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),n=i(37794),s=i(16582),o=i(76625),a=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:n,V2:s,V3:o,V4:a,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v1.local"),{pre:s,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:a=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),h=await r(u,c,d);return o("v1",a,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v1.local"),s=i(55589),{"v1.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=n(t);const u=r(i),c=t.export();return o(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),n=i(76331),s=i(15490),o=i(34089),a=i(17053);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a}},17053:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),o=n(r.generateKeyPair),a=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await a("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await o("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(6113),o=i(25054),a=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=a(e,c),h=o(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:n})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(6113),o=i(80094),a=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await o("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),n=i(49172),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(42421);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},42421:(e,t,i)=>{const r=i(39084),n=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:o}=i(74485),a=i(45445),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new o(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!a(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t))try{t=n.createPrivateKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(69946),{_checkPrivateKey:o}=i(42421),a=o.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=a(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:n}=i(42421),{post:s}=i(97362),o=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...a}={}){t=o(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,a,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v3.local"),s=i(42417),{pre:o,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=o("v3.local.",e);t=n(t);const f=s(u),m=t.export(),p=await r(d,h,m,f);return a("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v3.local"),s=i(55589),o=i(42417),{"v3.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),h=o(l),f=t.export();return a(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),n=i(58271),s=i(12596),o=i(5817),{generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),o=i(45445),a=i(70067),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!o(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return a(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),n=i(25054),s=i(55589),o=i(42417),a=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=s(e,h),m=n(i),p=o(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),a("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),n=i(42417),s=i(80094),o=i(45445),{bytesToKeyObject:a}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=a(e)}catch{}if(!o(e)||"private"===e.type)try{e=r(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),n=i(5816),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(80244);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:o,bytesToKeyObject:a}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:a,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return o("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(42417),o=i(69946),{_checkPrivateKey:a}=i(80244),l=a.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:a,...u}={}){const c=n(e,u),d=s(a);t=l(t);const h=r(i);return o("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),n=i(80094),{_checkPublicKey:s}=i(80244),{post:o}=i(97362),a=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=a(t);const c=r(l),{m:d,footer:h}=await n("v4.public.",e,void 0,64,t,c);return o("v4",s,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),n=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(n.isProd?"":`-${n.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),n=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const n=r(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:n.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*o.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class n{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=n},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let n=!(0,r.noColor)();function s(e,t){return i=>n?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){n=e??!(0,r.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),n=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),n=i(9678),s=i(15203),o=i(51053);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),n=i(66776),s=i(61570);var o=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),n=i(4866),s=i(98250);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),n=i(40786),s=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),n=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),n=i(70208),s=i(6231),o=i(70283),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=a){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=a){return f.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){n(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),n=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),n=i(42748),s=i(43383),o=i(87748),a=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,o.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),n=i(97742),s=i(4866),o=i(61570),a=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),n=i(74269),s=i(78109);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),n=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),n=i(51498);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),n=i(75556),s=i(17078),o=i(6667);function a(){const e=(0,r.memoryUsage)();return(0,o.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=a,t.memoryUsageMb=function(){return(0,n.sigFigs)(a()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const n=r(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&n.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=n.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),n=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,n]of(0,u.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,u.keys)(e))if(r[s]=t(s,e[s]),n++,(0,l.gt)(n,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),n=i(87561),s=i(70612),o=i(4866),a=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),n=i(39784),s=i(21142);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const n=i(5712),s=r(i(17718)),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),L=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),F=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))L().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,l.isEmpty)(n))return L().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){L().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){L().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(r,u)){L().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(L().info("killOldProcs(): killing",{reason:d,json:r}),o.push(N(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,n.pidExists)(r)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),n=t.getTime(),s={...e,cmd:r,startTime:n};return await i.writeJson_(s),L().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void L().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{L().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new j(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),n=i(7162),s=i(55568),o=i(51053);let a=!o.isElectron;t.setShortProcessNames=function(e){a=e},t.setProcessTitle=function(){try{const e=[a?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&o.isElectron||e.push((0,s.serviceName)());const t=e.join(o.isElectron?" ":"-");i(39369).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const n=r(i(97742)),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),S=i(46852),b=i(69317),P=i(9288),M=i(51053),_=i(71663),E=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return R(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],L))}());return(0,a.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[n.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),n.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},F=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),n.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",F.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(F,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===n.default.pid))||r.push({pid:n.default.pid,start:new Date(v.StartTs),cmd:"node "+n.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result)}t.psWinWmic=A},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),n=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),n=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...n)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=n,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return n.promise}(...n)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),n=i(82798);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(70612)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),n=i(4657),s=i(32370),o=i(19658),a=i(55568);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&(o.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,n.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const n=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return n.setShim=e=>{i=e},n.hasShim=()=>null!=i,n}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),n=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,n.isString)(e)?e:(0,r.stringify)(e))}){let a;const l=async i=>{const r=Date.now(),n=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-r),n},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),n=this.valueOf(this.store[r]);if(e===n)return{found:!0,index:r};e>n?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),n=i(58623),s=i(51081),o=i(18991),a=i(43414);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),n=i(18991);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+n+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),n=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),n=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,n.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(70612)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),n=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(92332)),s=i(75556);t.debounce=function(e,t){let i,r=[];const o=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return o.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class L{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new n(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=L,n=L,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),n=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}},r=new WeakMap,n=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=r.isTest?e:e||n}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,n,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,n,"f")?void 0:Date.now()-d(this,n,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===r&&h(this,o,i,"f"),d(this,a,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,n,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),n=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let n,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:n):(s=!0,n=(0,r.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>n,a.force=async()=>(await n,a()),a}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),n=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,u.gt0)(n)?(0,d.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=n?S.PermissivePromises:new S.Promises(i,(()=>n))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(n);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await E({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),n=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,r.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,n.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),n=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(n.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...T(r),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(n);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(n),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(r))}return n}t.childEnv=D},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(17718)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function L(e,i,r,n=0){const o=new Date,a=[];return(0,b.niceable)(i,r)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),L(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=F(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||n?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,a.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),L(n.default.spawn(e,t,s),e,t,i)},t.execFile=F,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95237:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=a(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),S=i(7162),b=i(91464),P=i(36079),M=i(91641),_=i(49379),E=i(98462),T=i(90524),x=i(94845),D=i(51053),k=i(69317),C=i(24905),O=i(52289),I=i(95298),L=(0,c.lazy)((()=>(0,S.mkLogger)("child.ChildService")));async function F(e){const t=(0,b.ensureSuffix)(e,".js"),i=E.BaseFile.projectRoot(),r=E.BaseFile.for(u.default.cwd()),n=(0,x.isPacked)()?[i.join("bin",t),D.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];n.push(r.join("dist","app",t));for(const e of n)if(null!=e&&!0===await e.isNonEmptyFile((0,x.isPacked)()?p.KB:128))return L().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:x.isPacked,paths:n.map(v.toS)}});return L().throw("Failed to find path to "+e,{paths:n,fatal:!0})}t.pathToService=F,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class A{static async mk_(e,t={}){const i=t.pathToService??await F(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new A(e,i,t)}constructor(e,t,i){r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,O.serviceExitTimeoutMs)(e),this.logger=(0,S.mkLogger)(this.name);const a=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&a.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,k.spawn)(u.default.execPath,a,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:o(this,r,"m",s).bind(this),onStderr:o(this,r,"m",n).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(T.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,b.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=A,r=new WeakSet,n=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},s=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),n=i(43414),s=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return o.join("$library",i.posixPathFrom(r));const n=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=n?o.join("$library",i.posixPathFrom(n)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),n=i(97742),s=i(42041),o=i(39938),a=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,o.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,a.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,n.exit)(0)})),e.parse(n.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),n=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,n.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),n=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(97742)),s=i(39938),o=i(38625);t.isDaemon=function(e){return(0,o.isTrue)(n.default.env.__is_daemon)||(0,o.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),n=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),n=i(82041),s=i(39938),o=i(38625),a=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,o.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,a.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),n=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),n=i(4866),s=i(66776),o=i(75556),a=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,o.toInt)(r.index),(0,o.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,o.clamp)(1,1e3,(0,o.toInt)(r,{defaultValue:1})),i=(0,o.clamp)(0,r-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new f(e,a,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(59694),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),r=T(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,o.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),n=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),n=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),n=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:o,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==o)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,a.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return b({year:n,month:s,day:o,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),n=i(39938),s=i(88491),o=i(21040),a=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,o.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,a.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),n=i(42748),s=i(47261),o=i(11944),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,a.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return n.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,a.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(n=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(o=>(0,y.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:o,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),o=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${T(s)}:${T(o)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,o.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function L(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?n.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(L(e,t),l.dayMs)},t.diffMillis=L,t.closeTo=function(e,t,i){return(0,u.mapOr)(L(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,o]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),a=(o-s)/(r+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=n.DateTime.fromMillis(s+a*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},n=(0,M.normalizeZone)(t);if(null!=e&&null!=n&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(n,r):D(e)?.setZone(n,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,o.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,E.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:F.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return F.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return F.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=L({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,h.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function L({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of F.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const t of s){const i=o(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=L;class F{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,r,"m",s).call(this))),o(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=L({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=F,r=new WeakSet,n=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},F.instance=(0,u.lazy)((()=>new F));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),n=i(75556),s=i(50140);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(o(e))||(0,n.gt0)(a(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(a(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),n=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),n=i(4866),s=i(88491),o=i(66776),a=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),o=r(),l=(0,a.toGt0)(r()),u=(0,a.toGt0)(r()),c=(0,a.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),n=i(59694),s=i(75556),o=i(36218),a=(0,r.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,n.sort)([...a().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),n=i(4866),s=i(92507),o=i(43414);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,o.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,L=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function F(e){return O(L().exec(e))}t.ianaZoneToOffsetMinutes=F,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=F(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(11944),a=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,o.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof n.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,o.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=n.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),a.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getFullYear()),a.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getMonth()+1),a.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function L(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,h.within)(1,12,e)}function F(e,t,i){return(0,u.gt0)(i)&&n.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||L(t,e))&&(!(0,u.gt0)(i)||F(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=L,t.validDay=F,t.validYMD=A},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),n=i(75556),s=i(44665),o=i(82701);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),n=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),n=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),n=i(39938),s=i(7162),o=i(14889),a=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,s.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,a.stdout_)("defaults",h,{timeoutMs:o.ShortCommandTimeoutMs});if((0,n.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),n=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),n=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),n=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),n=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),n=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),n=i(82798),s=i(3955),o=i(43414);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),n=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),n=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!n.isProd&&!(0,s.isPacked)()&&(0,r.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),n=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(87561)),s=i(49411),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,h.debom)(n.default.readFileSync(r)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(s))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),n=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),n=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),n=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),n=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),n=i(88491),s=i(19067),o=i(66776),a=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),S=i(6231),b=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,f.shortStringSha)(e.message,8,S.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,o=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,a.within)(r,o,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=b.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,o.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),n=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,n.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),n=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),n=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),n=i(87489);function s(e,...t){return n.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,r.lazy)((()=>s("exit")))},80313:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),n.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),n=i(4866),s=i(80313);function o(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,n.lazy)(o)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let n=!1;t.isSyncing=function(){return n},t.setIsSyncing=function(e){n!==e&&(n=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),n=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,n.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,n.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),L=i(75556),F=i(61570),A=i(20636),R=i(39784),N=i(7162),j=i(70283),B=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Z=i(21142),Y=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),ne=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Y.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,L.gt)(i,V.StartTs):r}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,L.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),n=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=n,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let n=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),n||(n=p(this,r,"m",f).call(this,e));n&&await this.save();const o=(0,k.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,L.gt)((0,H.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,F.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},n=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?n.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(n.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,n),this.save(),n)}}t.SharedState=be,n=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Z.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:n}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(n)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(n,n,"f",u)),ce.Settings.cacheDir.watchLater(p(n,n,"f",u)),ce.Settings.sharedStateDir.watchLater(p(n,n,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,ne.nativePathsEqlSync)(e,n.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(n.instance()),n.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(n,n,"f",l).call(n);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new n(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(87561)),s=r(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),n=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),L=i(98510),F=i(65113),A=i(44726),R=i(39784),N=i(82798),j=i(13779),B=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Z=i(91464),Y=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),ne=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new be(n,t);return Se().set(i,s),Se().set(n,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,L.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),n=i(17310),s=i(63526),o=i(3955);function a(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(n.ExtTypes.Video),t.isAssetFileExtension=a(n.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),n=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),n=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(49411)),s=r(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),n=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,n.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const n=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(n);const a=new c.FifoCache(1024),d=await(0,r.subscribe)(n,(async(e,i)=>{g().trace("callback",{nativePath:n,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:n}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(n,d,a,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,n.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new _(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),n=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,n.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),n=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,n.pick)(await(0,r.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),n=i(4866),s=i(39938),o=i(7162),a=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,n.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(o)?void 0:{ext:o,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),L=i(20636),F=i(82798),A=i(19658),R=i(1058),N=i(55568),j=i(91641),B=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,n,Math.max(Date.now(),w(this,n,"f",s)+1),"f",s),(0,E.compactBlanks)([H.TokenRadix.encode(w(this,n,"f",s)),N.serviceName.prior(),(0,F.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,F.toS)(e))?.groups?.pid)}static for(e){return w(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=n,n,(i=w(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(n,n,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(n,n,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),n=i(44726),s=i(82798),o=i(95725);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),L=i(95725),F=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,L.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,O.uid)(),n.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,n,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",a).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,n,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,n,"f")});const e=c(this,n,"f"),i=await(0,F.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,n,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,r,"m",a).call(this):!o&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,n,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,L.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,n,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,n,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=N,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),n=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(87561)),s=i(84492),o=i(76402),a=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,a.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,o.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44470)),s=r(i(87561)),o=i(76402),a=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(6005)),s=r(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),n=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),n=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),n=i(66776),s=i(79141),o=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,o.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),n=i(44726),s=i(82798);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),n=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,n.toNativePath_)(e),r=(0,n.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,n.toNativePath_)(e))===await(0,r.actualPath_)((0,n.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const r=await Promise.race([E(e,t),x(e,t)]);return t.halt(),r}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,r.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44470)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(g.isLinux?r===n:(0,m.equalsIgnoreCase)(r,n))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),O([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("โ€ฆ"),O([...n,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await n.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),L=i(14889),F=i(91464),A=i(46852),R=i(7383),N=i(21142),j=i(69317),B=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Z=i(19209),Y=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),ne=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:L.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,F.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,F.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,F.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,F.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,F.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,F.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:L.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(L.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(L.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,F.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const n=r(i(49411)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>n.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(n.default.join((0,t.execDir)(),"resources"),n.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=n.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),n=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),n=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),n=i(51081);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=T(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(n===h.Timeout&&(0,p.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const n=r(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return n.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),n=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const n=r(i(87561)),s=r(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(P(r),P(n));if(null==s||s>1)return"unmatched "+i+": "+r+" โ‰  "+n}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const n=r(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),n=i(6314);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(70612)),s=i(4866),o=i(66776),a=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,o.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),n=i(43947),s=i(66776),o=i(77296),a=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,o.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:a.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const a=s(i(93977)),l=o(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await a.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),n=i(14889),s=i(95725);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),n=i(34996);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44470)),s=r(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const o=i(93977),a=s(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),a.getHomeFolder(),a.getPicturesFolder(),a.getVideosFolder(),a.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,o.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),n=i(79403),s=i(32940),o=i(18295);t.getStatusSummary=async function(e={}){return(0,o.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const S=i(4866),b=i(11944),P=i(59694),M=i(43947),_=i(16475),E=i(77125),T=i(66776),x=i(23175),D=i(44726),k=i(20636),C=i(90957),O=i(39784),I=i(82798),L=i(13779),F=i(24945),A=i(94383),R=i(7162),N=i(12308),j=i(34996),B=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Z=i(62905),Y=i(18295),X=(0,S.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new j.Deferred(e);i.catch((t=>{v(this,n,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,n,"m",a).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,n,"f",l).push((0,D.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,n,"f",l).toA()}static addLoadingMsg(e){v(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,b.compact)((0,O.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,n,"f",h).entriesByCountDesc()}),(0,T.map)((0,L.leastBy)(e,(e=>[v(this,n,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,T.map)(e,(e=>v(this,n,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return v(this,n,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,E.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=n.summary();if(t.settledCountv(n,n,"f",o).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,a)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>n.onResultChange(),onError:()=>n.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,b.isEmpty)(e))return{};const[t,i]=(0,L.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,b.isNotEmpty)(i)&&(r.links=(0,b.uniqBy)(i)),(0,b.isNotEmpty)(t)&&(r.buttons=(0,b.uniqBy)(t)),r}t.HealthCheck=Q,n=Q,r=new WeakSet,a=function(){return(0,b.filterInPlace)(v(this,n,"f",s),(e=>!e.isPending)),v(this,n,"f",s)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Y.summarizeHealthChecksSync)({errors:v(this,n,"f",l),skipPending:v(this,n,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,n,!0,"f",u),t.state!==v(this,n,"f",c).last?.state&&v(this,n,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,x.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=n.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,b.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),o={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,B.ending)()?o:this.logger.tap({level:Z.HealthCheckLevelToLogLevel[r],msg:t,result:o})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,D.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,T.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},o={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new F.BoundedList(10)},u={value:!1},c={value:new F.BoundedList(10)},d={value:new F.BoundedList(100)},h={value:new A.CountingSet},f={value:[]},Q.all=(0,S.lazy)((()=>Object.freeze((0,P.sortBy)(v(n,n,"f",f),(e=>e.sortBy))))),Q.summary=(0,S.lazy)((()=>v(n,n,"m",m).call(n))),Q.resetDebounced=(0,N.debounce)((()=>n.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),n=i(77125),s=i(23022),o=i(55568),a=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,o.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,o.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,a.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),n=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(70612)),s=i(4866),o=i(36535),a=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,o.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),a.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:a.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),n=i(88491),s=i(43383),o=i(43947),a=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,o=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:o,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,a.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,o.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),n=i(57743),s=i(75556),o=i(33714),a=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,a.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:o.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),n=i(75556),s=i(7162),o=i(46852),a=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),n=i(43947),s=i(82798),o=i(4866),a=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),n=i(39938),s=i(88491),o=i(43947),a=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),n=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),n=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),n=i(57743),s=i(75556),o=i(8199),a=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),n=i(75556),s=i(31737),o=i(7162),a=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,o]=e.split("\t"),a=(0,n.toGt0)(s),l=(0,n.toGt0)(o);return null==a||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(57441)),s=i(4866),o=i(7162),a=i(43414),l=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function u(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:a.Settings.previewQuality.valueOrDefault,progressive:a.Settings.previewProgressive.valueOrDefault,mozjpeg:a.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),n=i(11944),s=i(43947),o=i(7162),a=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),n=i(11944),s=i(38625),o=i(88491),a=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),L=i(68107),F=i(53719),A=i(7218),R=i(49441),N=i(12737),j=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function B(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=B("extractMaxBitrate",e),n=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,n))return r.throw("invalid height: "+o,{ignorable:!0});const a=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return j().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=B("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const a=await r.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),h=null==d?void 0:await(0,A.dimensions)(n);if(null!=d&&d.mtimeMs>a&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:h}),n.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,F.commandTimeoutMs)()}),n.nativePath}async function q(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=B("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,O.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,n.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*o.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const r=B("transcode",e),n=$.get(t.nativePath);if(null!=n&&!(0,s.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:n.name}),n.promise.then((()=>t));const o=new y.Deferred(e.nativePath);if($.set(t.nativePath,o),!1===await G(e))return void r.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),n=(0,k.extractDurationSec)(r),s=(0,k.extractDurationSec)(i);return j().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,n={src:e,...V(e,d)},s=J(a,n.videoBitrateKbps,i),o=x.Settings.transcodeMaxDim.valueOrDefault,h=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(o)&&(0,c.gt)(h,o)){const e=(0,l.fitInside)(d.dimensions,{width:o,height:o});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:o}):(n.width=(0,u.roundEven)(e.width),n.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const o=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));n.dest=i,n.fps=(0,u.toGt0)(d.VideoFrameRate);const a=await o.observe((0,N.ffmpegTranscode_)(n));0!==a.code&&r.throw("transcode failed with code "+a.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&B("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),n=i(39938),s=i(38625),o=i(88491),a=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function L(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...L(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),n=i(4866),s=i(43414),o=i(59387);t.ffmpegThreads=(0,n.lazy)((()=>(0,r.toGt0)(s.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,o.maxCpus)()/4))))},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),n=i(69317),s=i(9288),o=i(51053),a=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),n=i(43414),s=i(69060);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),n=i(11944),s=i(88491),o=i(8199),a=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,a.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,o=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=o,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,o&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,o.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),n=i(59694),s=i(39938),o=i(38625),a=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),S=i(80294),b=i(4586),P=i(82341),M=i(42648),_=i(79015),E=i(98462),T=i(43414),x=i(10508),D=i(33501),k=i(19842),C=i(13700),O=i(74916);t.k=(0,r.rolazy)((()=>(0,x.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function L(e){const i=await(0,k.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,S.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,S.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function F(e,i,r,n){try{return(0,s.blank)(e)?void 0:D.L.for({str:e,l:await L(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function A(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await F((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,O.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=L,t.v=F,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await F(e,t,i);return(0,o.isTrue)(r?.ok)&&r instanceof D.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:O.UserTimeoutMs}),i=(0,c.map)((0,b.configDir)(),(e=>E.BaseFile.for(e))),r=(s=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return F(T.Settings[(0,t.k)().L].value,"Settings",O.UserTimeoutMs,e)}(e),()=>A(i?.join((0,t.k)().d),e),()=>A((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>A(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:O.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,n.sortBy)(s.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),n=i(4866),s=i(39938),o=i(10508);t.l=(0,n.lazy)((()=>(0,o.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),o=(0,t.l)().o.find((e=>e.k===n));if(null==o)throw new Error("Unknown key");return r.V2.verify(e,o)}},73435:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(11944),o=i(59694),a=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,o.sortBy)((0,s.uniq)(e.filter(b)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,a.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const S=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function b(e){return null!=e&&null!=S().exec(e)}t.isValidUid=b,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),n=i(39938),s=i(88491),o=i(43383),a=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),S=i(9483),b=i(72612),P=i(51053),M=i(71663),_=i(46573),E=i(75153),T=i(10508),x=i(73435);t.k=(0,o.defer)((()=>(0,T.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,o.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,o.defer)((()=>(0,m.thenMap)(k(),(e=>(0,x.toUID)(x.S.lc,e.join(",")))))),O=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,S.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(O)))}async function L(){return P.isLinux?(await I("lm")).map((e=>(0,x.toUID)(x.S.lm,e))):void 0}async function F(){return P.isLinux?(await I("lp")).map((e=>(0,x.toUID)(x.S.lp,e))):void 0}async function A(){return P.isLinux?(await I("lb")).map((e=>(0,x.toUID)(x.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,x.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function j(){return P.isWin?(0,x.toUID)(x.S.wm,await N()):void 0}t.win_machineGuid_=N;const B=(0,o.defer)((()=>(0,x.toUID)(x.S.cm,(0,E.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,x.toUID)(x.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,x.toUID)(x.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,x.toUID)(x.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,b.networkMacAddresses)().map((e=>(0,x.toUID)(x.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,x.toUID)(x.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[B,C,R,V,W,z,L,F,A,j,U,H],r=(0,a.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return D().tap({msg:"sids()",result:(0,x.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)q.add(t)},t.clearSids=function(){f.isTest&&q.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),n=i(88491),s=i(43947),o=i(1429),a=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),S=i(92781);function b(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=b,t.allRecentLogEntries=async function(e=50){(0,S.writeRecentLogEntries)();const t=(0,a.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(b(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const o=[],a=new w.LogReader(e,(e=>o.push(e)));for(await(0,f.untilTrue)((()=>a.ready()),{timeoutMs:10*n.secondMs});!a.complete()&&!a.hasErrors();){const e=a.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(o)&&(p.warn("Read error(s) for "+e,o),o.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,o.flatten)((0,a.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),n=i(4866),s=i(11944),o=i(39938),a=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),n=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),n=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,n.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),n=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),n=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(43947),a=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),o=i(4866),a=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),n=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),n=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),n=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),o=i(11944),a=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,o.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,a.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>n(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,a.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),n=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),n=i(61570),s=i(26588),o=i(44726),a=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["โ€ฆ"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},13755:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),n=i(49411),s=i(97742),o=i(92332),a=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),L=i(98968),F=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,L.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,L.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,L.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,L.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,F.readLogEntries)(e,{start:r,end:i}),(e=>(0,L.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),n=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),L=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class F extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,n,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,L.recentLogEntries)()),(0,L.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=F,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),n=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),n=i(51081),s=i(81666),o=i(95998),a=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),n=i(59694),s=i(61570),o=i(24945),a=i(9483);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),n=i(4866),s=i(66776),o=i(26302),a=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,n.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const n=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&n.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>n.push(e))),l.rootLoggers.set(n),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,o.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,a.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,n.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,n.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,n=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),n=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,r.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return n(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),n=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),n=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},76474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),n=i(3331);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},47858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httping=void 0;const r=i(88849),n=i(4866),s=i(7162),o=i(34996),a=i(19209),l=i(36297),u=(0,n.lazy)((()=>(0,s.mkLogger)("net.httping")));t.httping=function(e,t,i,n){const s=a.URI.from({scheme:"http",authority:e+":"+t,path:i}).toString(),c=new o.Deferred("ping "+s);return c.setTimeout(n),(0,r.get)(s,{timeout:n},(e=>{u().log(l.HttpStatusIs.error(e.statusCode)?"warn":"debug","ping",{latencyMs:Date.now()-c.startedAt,statusCode:e.statusCode}),e.resume(),c.resolve(e.statusCode)})).on("error",(e=>{u().warn("Failed to connect to "+s,e),c.resolve(void 0)})),c.promise}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),n=i(4866),s=i(11944),o=i(39938),a=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),a.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),a.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,o.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,o.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),n=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const M=(0,n.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),n=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),n=i(39938),s=i(43383),o=i(39784),a=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),n=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),n=i(4866),s=i(82798);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),n=i(7162),s=i(69317),o=i(63410),a=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(70612)),s=r(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),n=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),n=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),n=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),n=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),n=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),n=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),n=i(39784),s=i(9678),o=i(4586),a=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const o=s.join("old");try{const e=await r.renameYMDHMS_({subdir:o.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+o,e)}}t.mergeUserDataDirs_=async function(){const e=(0,o.configDir)();if(null==e)return;const t=a.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),n=i(39938),s=i(38625),o=i(88491),a=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){T(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&x()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(g.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*o.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,a.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,a.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},E={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?E:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function x(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=x},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),n=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},84490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),n=i(63774);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),n=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,n.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,n.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,n.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,n.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),n=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),L=i(51053),F=i(33407),A=i(11579),R=i(82590),N=i(55267),j=i(98788),B=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Z=i(29712),Y=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),ne=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Y.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:L.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,F.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,F.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Y.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ne.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(n.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(n.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),n=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>n.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:n.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(39938),a=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),E=i(79015),T=i(98462),x=i(98250),D=i(38846),k=i(23830),C=i(84161),O=i(44911),I=i(43414),L=i(95699),F=i(85560),A=i(98024),R=i(13060),N=i(31086),j=i(16704),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(F.SettingsToml)}async function V(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(T.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,R.readTomlFile_)((0,A.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function H(e){return(0,m.map)(z(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),a.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Z()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",q),(0,E.ee)().on("settingsChanged",q),I.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,o.blank)(e))return;const t=await T.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(n),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"old"}),await n.unwip_())}}async function Z(e=(0,A.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Y(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,o.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(o),{settings:o,warnings:s}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Z,t.writeAllSettings_=function(e){return K(x.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Z()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(x.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(z())?.unlink("trace")),(0,E.ee)().emit("clearCache"),L.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...O.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...O.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,h.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...re((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),n=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),n=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),n=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),n=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),n=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),n=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),n=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),n=i(91464);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),n=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),L=i(43414),F=i(69301),A=i(82590),R=i(63526),N=i(26352),j=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function B(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=B,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return B(this.src)}get isInferred(){return!B(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],n=r;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(n))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),o=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:o}),o}function H(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=n("tags",U(t,L.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??n("tags",U(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:n("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:n("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",H(e,t)))??(s?void 0:n("path",q(e)))??(L.Settings.useStatToInferDates.valueOrDefault?n("stat",await G(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return U(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),n=i(70283),s=i(98250),o=i(96593),a=i(27446);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(889),s=r(i(49411)),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),L=i(2023),F=i(55568),A=i(43414),R=i(13378),N=i(14889),j=i(91464),B=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Z=i(91854),Y=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),ne=i(45023),se=(0,a.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const ae=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,F.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=ae();return e.ended?ae.refresh():e}function ue(e=!1){return(0,d.map)(ae.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(ae.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,B.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,j.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),n=await e.sidecar(),s=(0,X.isImageMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,X.isVideoMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||o||a;return se().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function pe(e,i=!0){const r=x.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void se().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;se().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,X.normalizeMimetype),...n},a=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(n))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(r.History)),(0,L.assignNullishFields)(o.original,(0,f.pick)(o,...(0,f.keys)(n))),(0,f.assignFields)(o,n),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,$.getInferredHistoricValues)(a,e),(0,L.assignNullishFields)(o,o.inferred),o.Rotation=(0,Q.orientationToRotation)(o.Rotation),se().debug("readRawTags() final",{pf:r,inferred:o.inferred,pickedResult:(0,f.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,a);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=a?(0,Y.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Y.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,a);if(null==h)return void se().info("No capturedAt for "+e);!a&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,L.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[n,s]of(0,f.entries)(t)){const t=await me(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=x.PosixFile.for(t),n=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:n}),await le().write(r.nativePath,n,await fe(r)),A.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),oe&&(r.__instance=(0,O.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(87748),a=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,r=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[o])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,h.toS)(n)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}r.push([o,(0,l.gt0)(a)?a:u])}var n;return S(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),o=n(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),s=_(i);if(null==r||null==s||e===i)return;const o=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=r[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(h.toS),a=(0,u.values)(i).map(h.toS);if((0,n.includesAny)(o,a))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),n=i(82798),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),n=i(39938),s=i(75556),o=i(61570),a=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),n=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),n=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function L(e,i,r){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,T.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,o.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const r=O(e);(0,a.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=x(t.Actions.infer,r),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),L(i,n,s)},t.ensureHistoryRecords=L},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(9160)),s=i(889),o=i(4866),a=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,o.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,l.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),o=(0,d.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,d.normalizeZone)(o);if(null!=a)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),n=i(11944),s=i(39938),o=i(38625),a=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(66776),a=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,n.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),n=i(39938),s=i(66776),o=i(61570),a=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,n.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),n=i(82798),s=i(39607),o=i(71923),a=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),n=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,r.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),n=i(75556),s=i(43414);function o(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),n=i(39938),s=i(66776),o=i(21084),a=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),n=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(r.length)),l=s(i.slice(r.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),n=i(39938),s=i(88491),o=i(57743),a=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,r,await(0,h.rawInfo)(e));const s=b(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const n=(0,o.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),L=i(96593),F=i(17310),A=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),j=7;async function B(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,A.extractMakeAndModel)(await(0,L.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await B(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(F.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,o.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await B(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,a.sortBy)(i,(e=>(0,O.bname)(e))),n=(0,x.findFileIndex)(e,r);if(n<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(n-2*t,n),r.slice(n+1,n+1+2*t)],c=[],d=[];for(;(0,o.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,o.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await B(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,j);for(const t of e){const e=await(0,L.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(66776),a=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,a.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,a.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,o.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),n=i(39938),s=i(61570),o=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,o.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),n=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,a.orElse)(n,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(E(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:M(a,!1)),r}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),n=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),n=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),n=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?o.join(t,...n):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),n=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),n=i(39036);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),n=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),n=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),n=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await L()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function L(){const e=(0,n.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(I)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=L},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,n.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),n=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),n=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),L=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function F(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){F(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(F),T.Settings.scanPaths.watchLater(F),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return L().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(L().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),F()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,r.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),n=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),n=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),n=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),n=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),n=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(70612)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),L=i(20902),F=i(17875),A=i(79141),R=(i(79015),i(77390)),N=i(19653),j=i(3955),B=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Z=i(55412),Y=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),ne=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=n.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Z.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Z.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:se}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,N.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const n=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return ne().debug("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function ge(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Z.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,F.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,F.onError)("Timed out getting local volume metadata")));if(null==e)return void ne().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,F.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>q.isWin?(0,g.opt)((0,L.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),n=i(11944),s=i(39938),o=i(49049),a=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,a.toURI)(e),l=i.scheme===o.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===o.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),n=i(11944),s=i(75556),o=i(48652),a=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,a.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,o.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),n=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),n=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let n=!1;function s(){n&&(n=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return n},t.pause=function(e=!0){!1===e?s():n||(n=!0,(0,r.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),n=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),n.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=S();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,w());return t=(0,o.clamp)(1,n,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),n=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),n=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),n=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),n=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(17954),a=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,o.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,o.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,a.toS)(e)+"```"},t.b=function(e){return"**"+(0,a.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,a.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),n=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),n=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),n=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),n=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),n=i(33714),s=i(17078);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),n=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,n.isFunction)(e)&&(0,n.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of a){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),n=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),n=i(38625),s=i(61570),o=i(61715),a=i(84253);t.HealthCheckSections=(0,a.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,a.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&o.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),n=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),n=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),n=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=n.length;(0,r.filterInPlace)(n,(t=>e(i,t))),t=t||s!==n.length,0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),n=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,n){return!(null==n||!l(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,n.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),n=i(23175),s=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),n=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),n=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),n=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),n=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),n=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),n=i(61570),s=i(90957),o=i(21669);async function a(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{r&&(0,n.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,n=!0){const s=await a(e,i,n);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,r=!0){const n=i-Date.now();return n<=0?t.Timeout:a(e,n,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return l(e,n,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:n=!0}){const o=await a(e,i,n);return o===t.Timeout?(0,s.tot)(r):o}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),n=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),n=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=h[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,n)}t.isChrome=l,t.isSafari=function(e){return a(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),n=i(39938),s=i(87748),o=i(75556),a=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,o.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,a.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),n=i(11448),s=i(75556),o=i(33912),a=i(82669);function l(e,i){const r=(0,a.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,a.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(o.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),n=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),n=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},57567:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainService=void 0;const d=c(i(97742)),h=i(4866),f=i(7162),m=i(97198),p=i(34996),g=i(36079),y=i(28807),v=i(91641),w=i(95557),S=i(4691),b=i(2126),P=i(46027),M=i(95237),_=i(53525),E=i(49379),T=i(17875),x=i(56958),D=i(79015),k=i(98462),C=i(13699),O=i(90524),I=i(47858),L=i(43414),F=i(82041),A=i(19209),R=i(36297),N=c(i(35280)),j=i(67220),B=i(39938),z=i(38625),V=i(88491),W=i(87748),U=i(66776),H=i(75556),q=i(61570),G=i(82798),$=i(20990),J=i(47707);class K{constructor(){r.add(this),this.start=Date.now(),n.set(this,(0,h.lazy)((()=>(0,f.mkLogger)("MainService")))),this.httpPort=new p.Deferred("MainService.httpPort"),this.libraryDir=new p.Deferred("MainService.libraryDir"),s.set(this,void 0),o.set(this,void 0),this.setup=(0,h.lazy)((async()=>{l(this,s,await M.ChildService.mk_("web",{onStdout:e=>this.onWebout("stdout",e),onStderr:e=>this.onWebout("stderr",e),onData:e=>this.onWebData(e),onRestartPaused:()=>(0,b.exit)({reason:"Too many web service fatal errors",status:13})}),"f"),await(0,B.mapNotBlank)(L.Settings.pidFile.value,(async e=>{const t=k.BaseFile.for(e);u(this,n,"f").call(this).info("Writing to pidfile "+t,{pid:d.default.pid}),await t.writeText_((0,G.toS)(d.default.pid)),new w.EndableWrapper("remove pidfile",(()=>t.unlink()),v.EndableRanks.postdb)})),await this.service.ready;try{await(0,C.externalDirectoryCheck)()}catch(e){u(this,n,"f").call(this).warn("Failed to check external directory permissions",{error:e})}if(L.Settings.startPaused.valueOrDefault&&(u(this,n,"f").call(this).info("Settings.startPaused: pausing on startup."),await(0,x.broadcastPause)()),this.service.setInputHandler("--restart-sync",(()=>this.restartSync(!1))),this.service.setInputHandler(O.HealthCheckCommand,(()=>u(this,r,"m",a).call(this))),null==u(this,s,"f"))return(0,T.onError)("Failed to start webservice"+_.FatalErrorFlag);(0,D.ee)().on("resume",(()=>this.onResume())),this.httpPort.promise.then((e=>{const t=(0,N.default)(e),i=(1===t.length?" ":"\n - ")+t.map((e=>`${e}`)).join("\n - ");(0,m.consoleLog)(`PhotoStructure is ready:${i}`),L.Settings.exposeNetworkWithoutAuth.valueOrDefault||(0,m.consoleLog)("See https://photostructure.com/faq/remote-access/ to enable non-localhost access.")})),this.libraryDir.promise.then((e=>{(0,m.consoleLog)(`Your library is at <${A.URI.file(e)}>`)})),new w.EndableWrapper("shutdown notice",(()=>(0,m.consoleLog)("\nShutting down PhotoStructure...")),v.EndableRanks.first),(0,H.gt0)(L.Settings.healthCheckIntervalMs.valueOrDefault)&&new y.EndableInterval({name:"webSyncHealthChecks",intervalMs:L.Settings.healthCheckIntervalMs.valueOrDefault,callback:()=>u(this,r,"m",a).call(this)})})),this.service=new $.Service({name:"main"}),this.setup(),(0,P.setUnrefTimeout)((()=>{this.httpPort.isPending&&!(0,S.ending)()&&(0,m.consoleLog)("Please wait, setting up...")}),4*V.secondMs)}async webHealthCheck(){const e=this.httpPort.value;if(null!=e)try{const t=await(0,I.httping)("localhost",e,"/ping",3*V.secondMs);return!!R.HttpStatusIs.success(t)||(u(this,n,"f").call(this).warn("webHealthCheck(): web service returned "+t),!1)}catch(e){return u(this,n,"f").call(this).warn("webHealthCheck(): httping error: "+e),!1}else u(this,n,"f").call(this).info("webHealthCheck(): no-op, no http port set (web is starting up still)")}onWebout(e,t){return u(this,n,"f").call(this).info("onWebout",{pipe:e,error:t}),t??(t=""),/EADDRINUSE/i.test(t)||t.includes(_.WebFatalErrorFlag)||(0,E.isFatalError)(t)?((0,b.exit)({status:1,reason:"Web service error",error:t}),!0):(this.onWebData((0,W.parseJSON)(t)),!1)}async onWebData(e){(0,B.blank)(e)||(u(this,n,"f").call(this).info("onWebData",{input:e}),(0,U.map)(e[L.Settings.httpPort.key],(e=>{u(this,n,"f").call(this).info("Got HTTP port number from web service:"+e),L.Settings.httpPort.envValue=e,this.httpPort.maybeResolve(e)})),(0,z.mapBoolean)(e.pause,(e=>e?(0,j.pause)():(0,j.resume)())),await(0,z.mapTrue)(e.shutdown,(()=>(0,b.exit)({reason:"shutdown requested",status:0}))),await(0,z.mapTrue)(e.shutdownSync,(()=>this.shutdownSync())),(0,z.isTrue)(e.forceRestartSync)?await this.forceRestartSync():(0,z.isTrue)(e.restartSync)&&await this.restartSync(!1))}async shutdownSync(){const e=u(this,o,"f");return l(this,o,void 0,"f"),u(this,n,"f").call(this).info("shutdownSync()",{syncWasDefined:null!=e}),(0,g.end)(e)}async rebuildLibrary(){const e=u(this,o,"f")?.write("--force-rebuild-library");return null==e?u(this,n,"f").call(this).throw("Cannot schedule library rebuild: no sync!"):!1===e?u(this,n,"f").call(this).throw("Cannot schedule library rebuild: sync process is not writable!"):u(this,n,"f").call(this).info("Scheduled library rebuild")}async forceRestartSync(){return this.restartSync(!0)}async restartSync(e){const t=(0,f.mkLogger)("MainService.restartSync()");if((0,S.ending)())return void t.info("ending, no-op");const i=u(this,o,"f");if(t.info("priorSync",(0,U.map)(i,(e=>(0,q.pick)(e,"pid","name")))),await(0,g.end)(i),l(this,o,void 0,"f"),await(0,F.readSystemSettings)(),!F.libraryHasSettings.refresh())return void t.info("restartSync(): no library settings",{libraryDir:L.Settings.libraryDir.value});e&&await(0,J.rmStatDbDirs)();const r=l(this,o,await M.ChildService.mk_("sync"),"f");t.info("Started sync",(0,U.map)(r,(e=>(0,q.pick)(e,"pid","name"))))}async onResume(){null==u(this,o,"f")&&!0===await this.webHealthCheck()&&(u(this,n,"f").call(this).info("onResume(): starting sync."),await this.restartSync(!1))}}t.MainService=K,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){!1===await this.webHealthCheck()?await u(this,s,"f").restart():u(this,s,"f").runHealthCheck(),u(this,o,"f")?.runHealthCheck()},K.instance=(0,h.lazy)((()=>new K))},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),n=i(20902),s=i(94845),o=i(43414);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,s.isPacked)()&&!0===o.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const a=s(i(9856)),l=o(i(70612)),u=o(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),S=i(91641),b=i(95557),P=i(4691),M=i(52289),_=i(10408),E=i(27519),T=i(49379),x=i(17875),D=i(79015),k=i(12737),C=i(49857),O=i(7157),I=i(85352),L=i(9483),F=i(15203),A=i(51053),R=i(11944),N=i(39938),j=i(88491),B=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),H=i(82798),q=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,q.sentryEnabled)()&&null!=e&&!0!==(0,T.isDoNotSendError)(e)&&a.captureException(e)}t.installSentry=async function(e){try{return!!(0,q.sentryEnabled)()&&(a.init({dsn:A.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,x.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:A.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,q.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(E.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,T.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(E.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new b.EndableWrapper("EventFilter",(()=>this.end()),S.EndableRanks.first)}end(){return(0,V.map)(a.getCurrentHub().getClient(),(e=>e.close(5*j.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,H.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,F.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/j.secondMs,...e}}async function Q(){await(0,B.delay)(3*I.DefaultLogFlushMs);const e=await(0,O.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/j.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[L.LogLevels.fatal,"fatal"],[L.LogLevels.error,"error"],[L.LogLevels.warn,"warning"],[L.LogLevels.info,"info"],[L.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),S=i(7162),b=i(33148),P=i(55568),M=i(25516),_=i(38307),E=i(42041),T=i(95557),x=i(4691),D=i(2126),k=i(7383),C=i(70259),O=i(24905),I=i(44731),L=i(20902),F=i(10408),A=i(53525),R=i(49379),N=i(17875),j=i(79141),B=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),H=i(27644),q=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Z=i(39938),Y=i(88491),X=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{k.PromiseTimer.instance(),(0,B.ee)().on("resume",(()=>(0,J.resume)())),(0,B.ee)().on("pause",(()=>(0,J.pause)())),(0,B.ee)().on("exit",(()=>(0,D.exit)({reason:"exit() event",status:0})))}));class ne extends T.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,new Q.Latch),o.set(this,!1),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,n,(0,S.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,s,"f").promise}get isReady(){return m(this,s,"f").isResolved()}setInputHandler(e,t){m(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ne,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Z.mapNotBlank)((0,L.getEnv)("PS_FATAL_"+this.name),(e=>{throw new j.WrappedError(e,{fatal:!0})})),(0,Z.mapNotBlank)((0,L.getEnv)("PS_CRASH_"+this.name),(e=>{(0,X.later)((()=>{throw new j.WrappedError(e)}),5*Y.secondMs)})),(0,b.setProcessTitle)(),(0,P.isMainService)()&&await(0,H.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,x.ending)()?m(this,s,"f").reject():m(this,s,"f").resolve()}catch(e){console.error((0,F.errorToS)(e)),m(this,s,"f").reject((0,te.toErr)(e)),(0,D.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,F.errorToS)(e),A.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:E.version}))),this.setInputHandler(O.ChildServiceExitCommand,(()=>(0,X.later)((()=>(0,D.exit)({reason:O.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,n,"f").debug("onLine()",{line:e,ending:m(this,o,"f")||(0,x.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,a,"f").get(t);null==i?(m(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,n,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),n=i(7162),s=i(93813),o=i(29731),a=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,n.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function S(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:s.AssetVersion,AssetFileVersion:s.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,o.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),n=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(n.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+n),n):n}async function b(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=S,t.vacuumStatDbDirs=async function(){const e=await S();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(a.SqliteBase).mtimeMs()]));(null==i||ie.option("-p, --pidfile PIDFILE","Write a pidfile of the main process.").option("--stop","Shutdown daemonized PhotoStructure. Requires --pidfile").option("-d, --daemon","Run PhotoStructure as a daemon. Enabled by default when --pidfile is provided."),afterParse:async e=>{if((0,h.mapNotBlank)(e.pidfile,(e=>c.Settings.pidFile.envValue=e)),(0,f.isTrue)(e.stop)){if(!c.Settings.pidFile.hasValue()&&(await(0,d.readSystemSettings)(),!c.Settings.pidFile.hasValue()))return console.error("--stop requires --pidfile to be set."),o.default.exit(1);const e=u.BaseFile.for(c.Settings.pidFile.value);if(await e.notExists())return console.error("Pidfile "+e+" does not exist."),o.default.exit(1);const t=(0,m.toInt)(await e.readTextFile());return(0,m.gt0)(t)?(0,n.pidExists)(t)?(await(0,a.killPid)(t),o.default.exit(0)):(console.error("Pid "+t+" does not exist."),o.default.exit(1)):(console.error("Pidfile "+e+" is invalid."),o.default.exit(1))}if(!(0,f.isTrue)(o.default.env.__is_daemon)&&((0,f.isTrue)(e.daemon)||c.Settings.pidFile.hasValue())){const e=o.default.argv.findIndex((e=>!e.includes("npx")&&!e.includes("node"))),t=o.default.argv.slice(-1===e?0:e),i=process.execPath,r={...(0,l.childEnv)(),__is_daemon:"1"},n=(0,s.spawn)(i,t,{env:r,detached:!0,shell:!0});return n.unref(),console.log("Daemonized PhotoStructure.",{pid:n.pid,args:t}),o.default.exit(0)}}}},51731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(43414),n=i(38625);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,n.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),n=i(85297),s=i(43414),o=i(38625);function a(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(a()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return a()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),a()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,o.isTrue)(e.error),i=(0,o.isTrue)(e.warn),r=(0,o.isTrue)(e.info)||(0,o.isTrue)(e.verbose)||(0,o.isTrue)(e.v),l=(0,o.isTrue)(e.debug),u=(0,o.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,o.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,a()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},50763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(23830),n=i(38625);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,n.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},38381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PauseSyncArg=void 0;const r=i(43414),n=i(38625);t.PauseSyncArg={beforeParse:e=>e.option("--pauseSync","Pause sync processing until manually resumed via the system tray or nav menu."),afterParse:e=>{(0,n.isTrue)(e.pauseSync)&&(r.Settings.startPaused.envValue=!0)}}},75965:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MainArgs=void 0;try{i(34261).install()}catch{}const r=i(37980),n=i(37445),s=i(43414),o=i(38625),a=i(7127),l=i(57567),u=i(44),c=i(51731),d=i(92045),h=i(50763),f=i(38381);t.MainArgs={beforeParse:e=>e.option("--quiet","Don't emit lifecycle messages to stdout from the main service."),afterParse:e=>{(0,o.isTrue)(e.quiet)&&(s.Settings.quiet.tmpValue=!0)}},async function(){try{await new r.CLI(a.ServiceNames.main).add(t.MainArgs,c.ExposeArg,f.PauseSyncArg,u.DaemonArgs,h.NoFilterArg,n.WriteSettingsArg,d.LogArgs).parse(),new l.MainService}catch(e){console.error("Failed to start:")}}()},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},5712:e=>{"use strict";e.exports=require("batch-cluster")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},42748:e=>{"use strict";e.exports=require("luxon")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},88849:e=>{"use strict";e.exports=require("node:http")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(75965);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(74485),{decode:s}=i(87536),o=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:a,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==a&&"public"!==a)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:a};if("local"===a)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=s(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?o(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:o,notBefore:a,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(a))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.kid must be a string");c.kid=o}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),n=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:o,issuer:a,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.issuer must be a string");if(d.iss!==a)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.subject must be a string");if(d.sub!==o)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),n=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:n}=i(74485),s=i(88277),{decode:o}=i(87536),a=i(91225);e.exports={post:function(e,t,i,r,n,o,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:o?.length?o:void 0,version:e,purpose:l}:n}const u=a(n);return s(i,u),r?{payload:u,footer:o?.length?o:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:a}=t.slice(e.length).split(".");try{r(a<=2),i=o(i),s=o(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},45112:(e,t,i)=>{const r=i(6113),n=i(16464),s=i(97540),o=i(45018),{PasetoDecryptionFailed:a}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",a=m(e,r.randomBytes(32)).subarray(0,32),l=a.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,a.subarray(16)),y=s(n,a,p,t),v=m(y,f);return o(n,t,a,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),o=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=s("v1.local.",r,o,t),v=m(g,p);if(!l(n,v))throw new a("decryption failed");const w=await y(o,f,r.subarray(16));if(!w)throw new a("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const a="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),S=s(a,l,w,t,n),b=m(S,p);return o(a,t,l,w,b)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),o=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),S=s("v3.local.",n,u,t,r),b=m(S,g);if(!l(o,b))throw new a("decryption failed");const P=await y(u,v,w);if(!P)throw new a("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:n}=i(35740);n||(n=e=>null!=e&&e instanceof r),e.exports=n},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const n=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(n*t);case"day":case"days":case"d":return Math.round(864e5*n);case"week":case"weeks":case"w":return Math.round(6048e5*n);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*n)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:n}=i(39084),s=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),n=i(97540),s=i(45018);e.exports=async function(e,t,i,o,a,l,u){const c=n(u,e,t,i,l),d=await r(o,c,a);return s(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),n=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:n}=i(45112),s=i(97540),{pre:o}=i(97362);e.exports=async function(e,t,i,a,l,u,c){const{raw:d,f:h}=o(e,t),f=d.subarray(0,-a),m=d.subarray(-a),p=s(c,e,f,h,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),n=i(37794),s=i(16582),o=i(76625),a=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:n,V2:s,V3:o,V4:a,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v1.local"),{pre:s,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:a=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),h=await r(u,c,d);return o("v1",a,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v1.local"),s=i(55589),{"v1.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=n(t);const u=r(i),c=t.export();return o(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),n=i(76331),s=i(15490),o=i(34089),a=i(17053);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a}},17053:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),o=n(r.generateKeyPair),a=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await a("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await o("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(6113),o=i(25054),a=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=a(e,c),h=o(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:n})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(6113),o=i(80094),a=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await o("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),n=i(49172),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(42421);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},42421:(e,t,i)=>{const r=i(39084),n=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:o}=i(74485),a=i(45445),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new o(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!a(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t))try{t=n.createPrivateKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(69946),{_checkPrivateKey:o}=i(42421),a=o.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=a(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:n}=i(42421),{post:s}=i(97362),o=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...a}={}){t=o(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,a,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),n=i(29744).bind(void 0,"v3.local"),s=i(42417),{pre:o,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=o("v3.local.",e);t=n(t);const f=s(u),m=t.export(),p=await r(d,h,m,f);return a("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),n=i(29744).bind(void 0,"v3.local"),s=i(55589),o=i(42417),{"v3.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),h=o(l),f=t.export();return a(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),n=i(58271),s=i(12596),o=i(5817),{generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:s}=i(74485),o=i(45445),a=i(70067),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!o(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return a(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),n=i(25054),s=i(55589),o=i(42417),a=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=s(e,h),m=n(i),p=o(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),a("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),n=i(42417),s=i(80094),o=i(45445),{bytesToKeyObject:a}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=a(e)}catch{}if(!o(e)||"private"===e.type)try{e=r(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),n=i(5816),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(80244);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:o,bytesToKeyObject:a}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:a,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return o("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),n=i(55589),s=i(42417),o=i(69946),{_checkPrivateKey:a}=i(80244),l=a.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:a,...u}={}){const c=n(e,u),d=s(a);t=l(t);const h=r(i);return o("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),n=i(80094),{_checkPublicKey:s}=i(80244),{post:o}=i(97362),a=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=a(t);const c=r(l),{m:d,footer:h}=await n("v4.public.",e,void 0,64,t,c);return o("v4",s,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),n=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(n.isProd?"":`-${n.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),n=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const n=r(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),E=i(53719);class T extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:n.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=T,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*o.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class n{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=n},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let n=!(0,r.noColor)();function s(e,t){return i=>n?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){n=e??!(0,r.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),n=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),n=i(9678),s=i(15203),o=i(51053);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),n=i(66776),s=i(61570);var o=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),n=i(4866),s=i(98250);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),n=i(40786),s=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),n=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),n=i(70208),s=i(6231),o=i(70283),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=a){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=a){return f.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){n(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),n=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),n=i(42748),s=i(43383),o=i(87748),a=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,o.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),n=i(97742),s=i(4866),o=i(61570),a=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),n=i(74269),s=i(78109);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),n=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),n=i(51498);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),n=i(75556),s=i(17078),o=i(6667);function a(){const e=(0,r.memoryUsage)();return(0,o.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=a,t.memoryUsageMb=function(){return(0,n.sigFigs)(a()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const n=r(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&n.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=n.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),n=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,n]of(0,u.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,u.keys)(e))if(r[s]=t(s,e[s]),n++,(0,l.gt)(n,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),n=i(87561),s=i(70612),o=i(4866),a=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),n=i(39784),s=i(21142);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const n=i(5712),s=r(i(17718)),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),E=i(46027),T=i(4586),x=i(17875),D=i(98462),k=i(25015),C=i(3955),O=i(51053),I=i(71663),L=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),F=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))L().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,l.isEmpty)(n))return L().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){L().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){L().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(r,u)){L().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(L().info("killOldProcs(): killing",{reason:d,json:r}),o.push(N(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,x.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,n.pidExists)(r)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),n=t.getTime(),s={...e,cmd:r,startTime:n};return await i.writeJson_(s),L().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void L().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{L().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,T.configDir)(),(e=>new j(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),n=i(7162),s=i(55568),o=i(51053);let a=!o.isElectron;t.setShortProcessNames=function(e){a=e},t.setProcessTitle=function(){try{const e=[a?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&o.isElectron||e.push((0,s.serviceName)());const t=e.join(o.isElectron?" ":"-");i(39369).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const n=r(i(97742)),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),S=i(46852),b=i(69317),P=i(9288),M=i(51053),_=i(71663),E=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>T(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=T,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return R(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],L))}());return(0,a.sortBy)(e.filter(T),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[n.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),n.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",O(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},F=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),n.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",F.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(F,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===n.default.pid))||r.push({pid:n.default.pid,start:new Date(v.StartTs),cmd:"node "+n.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result)}t.psWinWmic=A},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),n=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),n=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...n)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=n,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return n.promise}(...n)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),n=i(82798);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(70612)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),n=i(4657),s=i(32370),o=i(19658),a=i(55568);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&(o.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,n.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const n=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return n.setShim=e=>{i=e},n.hasShim=()=>null!=i,n}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),n=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,n.isString)(e)?e:(0,r.stringify)(e))}){let a;const l=async i=>{const r=Date.now(),n=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-r),n},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),n=this.valueOf(this.store[r]);if(e===n)return{found:!0,index:r};e>n?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),n=i(58623),s=i(51081),o=i(18991),a=i(43414);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),n=i(18991);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+n+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['โ€˜โ€™].*['โ€˜โ€™]$/,x=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),n=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),n=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,n.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(70612)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),n=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(92332)),s=i(75556);t.debounce=function(e,t){let i,r=[];const o=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return o.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),E=i(26588),T=i(46234),x=i(21669),D=i(7162),k=i(49379),C=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class L{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new n(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=L,n=L,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),n=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}},r=new WeakMap,n=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=r.isTest?e:e||n}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,n,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,n,"f")?void 0:Date.now()-d(this,n,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===r&&h(this,o,i,"f"),d(this,a,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,n,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),n=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let n,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:n):(s=!0,n=(0,r.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>n,a.force=async()=>(await n,a()),a}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),n=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,u.gt0)(n)?(0,d.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=n?S.PermissivePromises:new S.Promises(i,(()=>n))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(n);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await E({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),n=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,r.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,n.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),n=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function T(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(n.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=T,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let x=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...T(r),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(n);if((0,m.isLogged)("debug")&&!x){x=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(n),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(r))}return n}t.childEnv=D},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(17718)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),E=i(49379),T=i(79141),x=i(83837),D=i(95976),k=i(10347),C=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,x.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function L(e,i,r,n=0){const o=new Date,a=[];return(0,b.niceable)(i,r)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),L(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=F(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,x.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||n?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,a.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??E.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),L(n.default.spawn(e,t,s),e,t,i)},t.execFile=F,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95237:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=a(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),S=i(7162),b=i(91464),P=i(36079),M=i(91641),_=i(49379),E=i(98462),T=i(90524),x=i(94845),D=i(51053),k=i(69317),C=i(24905),O=i(52289),I=i(95298),L=(0,c.lazy)((()=>(0,S.mkLogger)("child.ChildService")));async function F(e){const t=(0,b.ensureSuffix)(e,".js"),i=E.BaseFile.projectRoot(),r=E.BaseFile.for(u.default.cwd()),n=(0,x.isPacked)()?[i.join("bin",t),D.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];n.push(r.join("dist","app",t));for(const e of n)if(null!=e&&!0===await e.isNonEmptyFile((0,x.isPacked)()?p.KB:128))return L().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:x.isPacked,paths:n.map(v.toS)}});return L().throw("Failed to find path to "+e,{paths:n,fatal:!0})}t.pathToService=F,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class A{static async mk_(e,t={}){const i=t.pathToService??await F(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new A(e,i,t)}constructor(e,t,i){r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,O.serviceExitTimeoutMs)(e),this.logger=(0,S.mkLogger)(this.name);const a=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&a.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,k.spawn)(u.default.execPath,a,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:o(this,r,"m",s).bind(this),onStderr:o(this,r,"m",n).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(T.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,b.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=A,r=new WeakSet,n=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},s=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),n=i(43414),s=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),E=i(79141),T=i(45512),x=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return o.join("$library",i.posixPathFrom(r));const n=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=n?o.join("$library",i.posixPathFrom(n)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),n=i(97742),s=i(42041),o=i(39938),a=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,o.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,a.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":s.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+s.version+"\n"+p.DescriptionFooter))),(0,n.exit)(0)})),e.parse(n.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),n=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,n.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),n=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(97742)),s=i(39938),o=i(38625);t.isDaemon=function(e){return(0,o.isTrue)(n.default.env.__is_daemon)||(0,o.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),n=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),n=i(82041),s=i(39938),o=i(38625),a=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,o.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,a.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),n=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),n=i(4866),s=i(66776),o=i(75556),a=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,o.toInt)(r.index),(0,o.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,o.clamp)(1,1e3,(0,o.toInt)(r,{defaultValue:1})),i=(0,o.clamp)(0,r-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new f(e,a,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(59694),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),r=T(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,o.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),n=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),n=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),n=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:o,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==o)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,a.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return b({year:n,month:s,day:o,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),n=i(39938),s=i(88491),o=i(21040),a=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,o.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,a.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),n=i(42748),s=i(47261),o=i(11944),a=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),E=i(60299);function T(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class x{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,a.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tT(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return n.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new x(t.year,t.month,t.day)}}function D(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,a.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(n=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(o=>(0,y.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:o,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=x,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),o=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${T(s)}:${T(o)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?O(e):D(e,(0,E.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function O(e,t="-"){return(0,o.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>T(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new x(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function L(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?n.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,E.hasZone)(t)?C:k):void 0},t.datedToYMD=O,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(L(e,t),l.dayMs)},t.diffMillis=L,t.closeTo=function(e,t,i){return(0,u.mapOr)(L(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,o]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),a=(o-s)/(r+1),l=(0,E.getZoneName)(e),u=l===(0,E.getZoneName)(t)?l:void 0,c=n.DateTime.fromMillis(s+a*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,E.hasZone)(e)},n=(0,M.normalizeZone)(t);if(null!=e&&null!=n&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(n,r):D(e)?.setZone(n,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,o.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,E.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),E=i(45161),T=i(50140),x=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:F.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return F.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return F.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=L({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,h.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function L({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of F.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const t of s){const i=o(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=L;class F{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,r,"m",s).call(this))),o(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=L({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=F,r=new WeakSet,n=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},F.instance=(0,u.lazy)((()=>new F));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),n=i(75556),s=i(50140);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(o(e))||(0,n.gt0)(a(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(a(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),n=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),n=i(4866),s=i(88491),o=i(66776),a=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),o=r(),l=(0,a.toGt0)(r()),u=(0,a.toGt0)(r()),c=(0,a.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),n=i(59694),s=i(75556),o=i(36218),a=(0,r.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,n.sort)([...a().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),n=i(4866),s=i(92507),o=i(43414);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,o.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(39938),a=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-ยฑ+โˆ’])/,T=/[-โˆ’]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,L=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function F(e){return O(L().exec(e))}t.ianaZoneToOffsetMinutes=F,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=F(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(11944),a=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,o.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),E=(0,s.lazy)((()=>(0,o.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const x=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===x)return x;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof n.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,o.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=n.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return E().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return T(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),a.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getFullYear()),a.hourMs),O=(0,s.lazy)((()=>new Date(Date.now()+a.dayMs).getMonth()+1),a.hourMs);function I(e){return(0,h.within)(k(),C(),e)}function L(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,O()))&&(0,h.within)(1,12,e)}function F(e,t,i){return(0,u.gt0)(i)&&n.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return I(e)&&(!(0,u.gt0)(t)||L(t,e))&&(!(0,u.gt0)(i)||F(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),O.unset()}))})),t.validYear=I,t.validMonth=L,t.validDay=F,t.validYMD=A},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),n=i(75556),s=i(44665),o=i(82701);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),n=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),E=i(51510),T=i(10156),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),n=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),n=i(39938),s=i(7162),o=i(14889),a=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,s.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,a.stdout_)("defaults",h,{timeoutMs:o.ShortCommandTimeoutMs});if((0,n.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),n=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),n=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),n=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),n=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),n=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),n=i(82798),s=i(3955),o=i(43414);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),n=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),n=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!n.isProd&&!(0,s.isPacked)()&&(0,r.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),n=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(87561)),s=i(49411),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,h.debom)(n.default.readFileSync(r)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(s))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),n=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),n=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),n=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),n=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),n=i(88491),s=i(19067),o=i(66776),a=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),S=i(6231),b=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,f.shortStringSha)(e.message,8,S.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,o=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,a.within)(r,o,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=b.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,o.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),n=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,n.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),n=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),n=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),n=i(87489);function s(e,...t){return n.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,r.lazy)((()=>s("exit")))},80313:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),n.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),n=i(4866),s=i(80313);function o(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,n.lazy)(o)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let n=!1;t.isSyncing=function(){return n},t.setIsSyncing=function(e){n!==e&&(n=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),n=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,n.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,n.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),E=i(88491),T=i(43383),x=i(24603),D=i(16475),k=i(1429),C=i(87748),O=i(21040),I=i(66776),L=i(75556),F=i(61570),A=i(20636),R=i(39784),N=i(7162),j=i(70283),B=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Z=i(21142),Y=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),ne=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,Y.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,L.gt)(i,V.StartTs):r}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,L.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),n=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=n,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let n=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),n||(n=p(this,r,"m",f).call(this,e));n&&await this.save();const o=(0,k.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,L.gt)((0,H.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,x.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,F.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},n=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?n.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(n.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,n),this.save(),n)}}t.SharedState=be,n=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Z.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:n}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(n)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,T.defer)((()=>{ce.Settings.libraryDir.watchLater(p(n,n,"f",u)),ce.Settings.cacheDir.watchLater(p(n,n,"f",u)),ce.Settings.sharedStateDir.watchLater(p(n,n,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,ne.nativePathsEqlSync)(e,n.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(n.instance()),n.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(n,n,"f",l).call(n);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new n(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(87561)),s=r(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),n=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),E=i(39938),T=i(88491),x=i(24603),D=i(1429),k=i(87748),C=i(66776),O=i(75556),I=i(61570),L=i(98510),F=i(65113),A=i(44726),R=i(39784),N=i(82798),j=i(13779),B=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Z=i(91464),Y=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),ne=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new be(n,t);return Se().set(i,s),Se().set(n,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,L.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*T.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),n=i(17310),s=i(63526),o=i(3955);function a(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(n.ExtTypes.Video),t.isAssetFileExtension=a(n.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),n=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),n=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(49411)),s=r(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),n=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,n.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const n=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(n);const a=new c.FifoCache(1024),d=await(0,r.subscribe)(n,(async(e,i)=>{g().trace("callback",{nativePath:n,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:n}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(n,d,a,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,n.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new _(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),n=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,n.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),n=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,n.pick)(await(0,r.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),n=i(4866),s=i(39938),o=i(7162),a=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,n.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(o)?void 0:{ext:o,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),E=i(11944),T=i(37609),x=i(88491),D=i(24603),k=i(19067),C=i(66776),O=i(75556),I=i(23175),L=i(20636),F=i(82798),A=i(19658),R=i(1058),N=i(55568),j=i(91641),B=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,n,Math.max(Date.now(),w(this,n,"f",s)+1),"f",s),(0,E.compactBlanks)([H.TokenRadix.encode(w(this,n,"f",s)),N.serviceName.prior(),(0,F.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,F.toS)(e))?.groups?.pid)}static for(e){return w(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=n,n,(i=w(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(n,n,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:x.secondMs);S(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(n,n,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),n=i(44726),s=i(82798),o=i(95725);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),E=i(17354),T=i(79015),x=i(3955),D=i(8177),k=i(43414),C=i(91464),O=i(37086),I=i(59873),L=i(95725),F=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,x.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,x.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,L.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,O.uid)(),n.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,n,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",a).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,n,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,n,"f")});const e=c(this,n,"f"),i=await(0,F.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,n,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,r,"m",a).call(this):!o&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,T.ee)().emit("fileChanged",this.targetNativePath),u(this,n,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,L.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,n,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,n,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=N,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),n=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(87561)),s=i(84492),o=i(76402),a=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,a.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,o.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44470)),s=r(i(87561)),o=i(76402),a=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(6005)),s=r(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),n=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),n=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),n=i(66776),s=i(79141),o=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,o.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),n=i(44726),s=i(82798);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),n=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,n.toNativePath_)(e),r=(0,n.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,n.toNativePath_)(e))===await(0,r.actualPath_)((0,n.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return T(e,i,t);const r=await Promise.race([E(e,t),x(e,t)]);return t.halt(),r}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function T(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,r.basename)))return!0}return!1}async function x(e,t){const i=await(0,m.readdir)(e);return null!=i&&T(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44470)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function T(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(g.isLinux?r===n:(0,m.equalsIgnoreCase)(r,n))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),O([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("โ€ฆ"),O([...n,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await n.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),E=i(75556),T=i(61570),x=i(20636),D=i(49049),k=i(17078),C=i(82798),O=i(13779),I=i(7162),L=i(14889),F=i(91464),A=i(46852),R=i(7383),N=i(21142),j=i(69317),B=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Z=i(19209),Y=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),ne=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:L.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,F.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,F.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,F.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,F.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,F.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,F.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:L.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(L.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(L.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,F.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const n=r(i(49411)),s=r(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>n.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(n.default.join((0,t.execDir)(),"resources"),n.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=n.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),n=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),n=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),n=i(51081);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=T(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(n===h.Timeout&&(0,p.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):T(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=T},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const n=r(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return n.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),n=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const n=r(i(87561)),s=r(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(P(r),P(n));if(null==s||s>1)return"unmatched "+i+": "+r+" โ‰  "+n}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const n=r(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),n=i(6314);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(70612)),s=i(4866),o=i(66776),a=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,o.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),n=i(43947),s=i(66776),o=i(77296),a=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,o.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:a.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const a=s(i(93977)),l=o(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await a.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function E(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await E(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await E(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=E},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),n=i(14889),s=i(95725);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),n=i(34996);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44470)),s=r(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const o=i(93977),a=s(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),a.getHomeFolder(),a.getPicturesFolder(),a.getVideosFolder(),a.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,o.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),n=i(79403),s=i(32940),o=i(18295);t.getStatusSummary=async function(e={}){return(0,o.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const S=i(4866),b=i(11944),P=i(59694),M=i(43947),_=i(16475),E=i(77125),T=i(66776),x=i(23175),D=i(44726),k=i(20636),C=i(90957),O=i(39784),I=i(82798),L=i(13779),F=i(24945),A=i(94383),R=i(7162),N=i(12308),j=i(34996),B=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Z=i(62905),Y=i(18295),X=(0,S.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new j.Deferred(e);i.catch((t=>{v(this,n,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,n,"m",a).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,n,"f",l).push((0,D.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,n,"f",l).toA()}static addLoadingMsg(e){v(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,b.compact)((0,O.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return X().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,n,"f",h).entriesByCountDesc()}),(0,T.map)((0,L.leastBy)(e,(e=>[v(this,n,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,T.map)(e,(e=>v(this,n,"f",h).incr(e.msg))),X().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return v(this,n,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,E.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=n.summary();if(t.settledCountv(n,n,"f",o).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,a)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>n.onResultChange(),onError:()=>n.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,b.isEmpty)(e))return{};const[t,i]=(0,L.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,b.isNotEmpty)(i)&&(r.links=(0,b.uniqBy)(i)),(0,b.isNotEmpty)(t)&&(r.buttons=(0,b.uniqBy)(t)),r}t.HealthCheck=Q,n=Q,r=new WeakSet,a=function(){return(0,b.filterInPlace)(v(this,n,"f",s),(e=>!e.isPending)),v(this,n,"f",s)},m=function(e){const t=X().tap({level:"info",msg:"#summary()",result:(0,Y.summarizeHealthChecksSync)({errors:v(this,n,"f",l),skipPending:v(this,n,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,n,!0,"f",u),t.state!==v(this,n,"f",c).last?.state&&v(this,n,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){X().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,x.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=n.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,b.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),o={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,B.ending)()?o:this.logger.tap({level:Z.HealthCheckLevelToLogLevel[r],msg:t,result:o})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,D.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,T.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},o={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new F.BoundedList(10)},u={value:!1},c={value:new F.BoundedList(10)},d={value:new F.BoundedList(100)},h={value:new A.CountingSet},f={value:[]},Q.all=(0,S.lazy)((()=>Object.freeze((0,P.sortBy)(v(n,n,"f",f),(e=>e.sortBy))))),Q.summary=(0,S.lazy)((()=>v(n,n,"m",m).call(n))),Q.resetDebounced=(0,N.debounce)((()=>n.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),n=i(77125),s=i(23022),o=i(55568),a=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,o.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,o.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,a.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),n=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(70612)),s=i(4866),o=i(36535),a=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,o.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),a.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:a.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),n=i(88491),s=i(43383),o=i(43947),a=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,o=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:o,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,a.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,o.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),n=i(57743),s=i(75556),o=i(33714),a=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,a.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:o.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),n=i(75556),s=i(7162),o=i(46852),a=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),n=i(43947),s=i(82798),o=i(4866),a=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),n=i(39938),s=i(88491),o=i(43947),a=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),n=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),n=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),n=i(57743),s=i(75556),o=i(8199),a=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),n=i(75556),s=i(31737),o=i(7162),a=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,o]=e.split("\t"),a=(0,n.toGt0)(s),l=(0,n.toGt0)(o);return null==a||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(57441)),s=i(4866),o=i(7162),a=i(43414),l=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function u(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:a.Settings.previewQuality.valueOrDefault,progressive:a.Settings.previewProgressive.valueOrDefault,mozjpeg:a.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),n=i(11944),s=i(43947),o=i(7162),a=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),n=i(11944),s=i(38625),o=i(88491),a=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),E=i(6667),T=i(49586),x=i(43414),D=i(68567),k=i(27947),C=i(96593),O=i(27446),I=i(84685),L=i(68107),F=i(53719),A=i(7218),R=i(49441),N=i(12737),j=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function B(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=B("extractMaxBitrate",e),n=x.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,n))return r.throw("invalid height: "+o,{ignorable:!0});const a=(0,D.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return j().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=B("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const a=await r.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),h=null==d?void 0:await(0,A.dimensions)(n);if(null!=d&&d.mtimeMs>a&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:h}),n.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,F.commandTimeoutMs)()}),n.nativePath}async function q(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=B("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,O.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,n.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*o.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const r=B("transcode",e),n=$.get(t.nativePath);if(null!=n&&!(0,s.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:n.name}),n.promise.then((()=>t));const o=new y.Deferred(e.nativePath);if($.set(t.nativePath,o),!1===await G(e))return void r.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),n=(0,k.extractDurationSec)(r),s=(0,k.extractDurationSec)(i);return j().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,n={src:e,...V(e,d)},s=J(a,n.videoBitrateKbps,i),o=x.Settings.transcodeMaxDim.valueOrDefault,h=(0,E.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(o)&&(0,c.gt)(h,o)){const e=(0,l.fitInside)(d.dimensions,{width:o,height:o});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:o}):(n.width=(0,u.roundEven)(e.width),n.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const o=new T.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));n.dest=i,n.fps=(0,u.toGt0)(d.VideoFrameRate);const a=await o.observe((0,N.ffmpegTranscode_)(n));0!==a.code&&r.throw("transcode failed with code "+a.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&B("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),n=i(39938),s=i(38625),o=i(88491),a=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),E=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function T(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const x=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await T();if(null==e)return void E().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=x.exec(t.result)?.[1];return E().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function O(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function L(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=O,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await T(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...O(t),...L(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){E().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return E().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return E().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),n=i(4866),s=i(43414),o=i(59387);t.ffmpegThreads=(0,n.lazy)((()=>(0,r.toGt0)(s.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,o.maxCpus)()/4))))},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),n=i(69317),s=i(9288),o=i(51053),a=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),n=i(43414),s=i(69060);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),n=i(11944),s=i(88491),o=i(8199),a=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,a.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,o=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=o,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,o&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,o.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),n=i(59694),s=i(39938),o=i(38625),a=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),S=i(80294),b=i(4586),P=i(82341),M=i(42648),_=i(79015),E=i(98462),T=i(43414),x=i(10508),D=i(33501),k=i(19842),C=i(13700),O=i(74916);t.k=(0,r.rolazy)((()=>(0,x.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function L(e){const i=await(0,k.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,S.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,S.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function F(e,i,r,n){try{return(0,s.blank)(e)?void 0:D.L.for({str:e,l:await L(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function A(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await F((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,O.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=L,t.v=F,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await F(e,t,i);return(0,o.isTrue)(r?.ok)&&r instanceof D.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:O.UserTimeoutMs}),i=(0,c.map)((0,b.configDir)(),(e=>E.BaseFile.for(e))),r=(s=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return F(T.Settings[(0,t.k)().L].value,"Settings",O.UserTimeoutMs,e)}(e),()=>A(i?.join((0,t.k)().d),e),()=>A((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>A(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:O.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,n.sortBy)(s.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),n=i(4866),s=i(39938),o=i(10508);t.l=(0,n.lazy)((()=>(0,o.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),o=(0,t.l)().o.find((e=>e.k===n));if(null==o)throw new Error("Unknown key");return r.V2.verify(e,o)}},73435:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(11944),o=i(59694),a=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,o.sortBy)((0,s.uniq)(e.filter(b)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,a.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const S=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function b(e){return null!=e&&null!=S().exec(e)}t.isValidUid=b,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),n=i(39938),s=i(88491),o=i(43383),a=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),S=i(9483),b=i(72612),P=i(51053),M=i(71663),_=i(46573),E=i(75153),T=i(10508),x=i(73435);t.k=(0,o.defer)((()=>(0,T.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,o.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,o.defer)((()=>(0,m.thenMap)(k(),(e=>(0,x.toUID)(x.S.lc,e.join(",")))))),O=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,S.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(O)))}async function L(){return P.isLinux?(await I("lm")).map((e=>(0,x.toUID)(x.S.lm,e))):void 0}async function F(){return P.isLinux?(await I("lp")).map((e=>(0,x.toUID)(x.S.lp,e))):void 0}async function A(){return P.isLinux?(await I("lb")).map((e=>(0,x.toUID)(x.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,x.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function j(){return P.isWin?(0,x.toUID)(x.S.wm,await N()):void 0}t.win_machineGuid_=N;const B=(0,o.defer)((()=>(0,x.toUID)(x.S.cm,(0,E.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,x.toUID)(x.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,x.toUID)(x.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,x.toUID)(x.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,b.networkMacAddresses)().map((e=>(0,x.toUID)(x.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,x.toUID)(x.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[B,C,R,V,W,z,L,F,A,j,U,H],r=(0,a.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return D().tap({msg:"sids()",result:(0,x.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)q.add(t)},t.clearSids=function(){f.isTest&&q.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),n=i(88491),s=i(43947),o=i(1429),a=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),S=i(92781);function b(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=b,t.allRecentLogEntries=async function(e=50){(0,S.writeRecentLogEntries)();const t=(0,a.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(b(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const o=[],a=new w.LogReader(e,(e=>o.push(e)));for(await(0,f.untilTrue)((()=>a.ready()),{timeoutMs:10*n.secondMs});!a.complete()&&!a.hasErrors();){const e=a.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(o)&&(p.warn("Read error(s) for "+e,o),o.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,o.flatten)((0,a.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),n=i(4866),s=i(11944),o=i(39938),a=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),n=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),n=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,n.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),n=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),n=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(43947),a=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),o=i(4866),a=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),n=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),n=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),n=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),o=i(11944),a=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,o.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,a.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>n(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,a.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),n=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),n=i(61570),s=i(26588),o=i(44726),a=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["โ€ฆ"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},13755:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),n=i(49411),s=i(97742),o=i(92332),a=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),E=i(57400),T=i(3955),x=i(43414),D=i(71951),k=i(85352),C=i(81647),O=i(95976),I=i(9483),L=i(98968),F=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,L.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,L.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,L.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,L.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,F.readLogEntries)(e,{start:r,end:i}),(e=>(0,L.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),n=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),E=i(40374),T=i(83837),x=i(43414),D=i(74269),k=i(85352),C=i(81647),O=i(95976),I=i(48924),L=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class F extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.onEnds.push((()=>c(this,n,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,L.recentLogEntries)()),(0,L.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=F,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),n=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),n=i(51081),s=i(81666),o=i(95998),a=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),n=i(59694),s=i(61570),o=i(24945),a=i(9483);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),n=i(4866),s=i(66776),o=i(26302),a=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),E=i(27998);t.setupLogger=(0,n.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const n=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&n.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>n.push(e))),l.rootLoggers.set(n),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,o.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),T(),(0,a.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,n.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new E.PlaintextLogFormatter)}));const T=(0,n.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,n=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),n=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,r.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return n(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),n=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),n=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},76474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),n=i(3331);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},47858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httping=void 0;const r=i(88849),n=i(4866),s=i(7162),o=i(34996),a=i(19209),l=i(36297),u=(0,n.lazy)((()=>(0,s.mkLogger)("net.httping")));t.httping=function(e,t,i,n){const s=a.URI.from({scheme:"http",authority:e+":"+t,path:i}).toString(),c=new o.Deferred("ping "+s);return c.setTimeout(n),(0,r.get)(s,{timeout:n},(e=>{u().log(l.HttpStatusIs.error(e.statusCode)?"warn":"debug","ping",{latencyMs:Date.now()-c.startedAt,statusCode:e.statusCode}),e.resume(),c.resolve(e.statusCode)})).on("error",(e=>{u().warn("Failed to connect to "+s,e),c.resolve(void 0)})),c.promise}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),n=i(4866),s=i(11944),o=i(39938),a=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),a.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),a.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,o.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,o.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),n=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const M=(0,n.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),n=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),n=i(39938),s=i(43383),o=i(39784),a=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),n=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),n=i(4866),s=i(82798);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),n=i(7162),s=i(69317),o=i(63410),a=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(70612)),s=r(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),n=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),n=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),n=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),n=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),E=i(53719),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),n=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),n=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),n=i(39784),s=i(9678),o=i(4586),a=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const o=s.join("old");try{const e=await r.renameYMDHMS_({subdir:o.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+o,e)}}t.mergeUserDataDirs_=async function(){const e=(0,o.configDir)();if(null==e)return;const t=a.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),n=i(39938),s=i(38625),o=i(88491),a=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){T(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&x()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(g.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*o.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,a.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,a.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},E={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?E:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function x(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=x},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),n=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),n=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},84490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),n=i(63774);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),n=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,n.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,n.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,n.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,n.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),n=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),E=i(94794),T=i(7560),x=i(45005),D=i(20902),k=i(6565),C=i(80534),O=i(86613),I=i(15203),L=i(51053),F=i(33407),A=i(11579),R=i(82590),N=i(55267),j=i(98788),B=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Z=i(29712),Y=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),ne=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Y.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:L.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,F.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,F.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Y.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ne.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(n.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(n.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),n=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>n.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:n.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(39938),a=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),E=i(79015),T=i(98462),x=i(98250),D=i(38846),k=i(23830),C=i(84161),O=i(44911),I=i(43414),L=i(95699),F=i(85560),A=i(98024),R=i(13060),N=i(31086),j=i(16704),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(F.SettingsToml)}async function V(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(T.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,R.readTomlFile_)((0,A.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function H(e){return(0,m.map)(z(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),a.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Z()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",q),(0,E.ee)().on("settingsChanged",q),I.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,o.blank)(e))return;const t=await T.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(n),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"old"}),await n.unwip_())}}async function Z(e=(0,A.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Y(e){return Q(z(e))}async function X(e){await(0,M.setupLibraryDataDir_)((0,o.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(o),{settings:o,warnings:s}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Z,t.writeAllSettings_=function(e){return K(x.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=X,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Z()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(x.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(z())?.unlink("trace")),(0,E.ee)().emit("clearCache"),L.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...O.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...O.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,h.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...re((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),n=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),n=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),n=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),n=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),n=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),n=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),n=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),n=i(91464);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),n=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),E=i(68074),T=i(54809),x=i(64455),D=i(60299),k=i(3955),C=i(95725),O=i(63410),I=i(9483),L=i(43414),F=i(69301),A=i(82590),R=i(63526),N=i(26352),j=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function B(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=B,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return B(this.src)}get isInferred(){return!B(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],n=r;if((0,x.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(n))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),o=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:o}),o}function H(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=n("tags",U(t,L.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??n("tags",U(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:n("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:n("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",H(e,t)))??(s?void 0:n("path",q(e)))??(L.Settings.useStatToInferDates.valueOrDefault?n("stat",await G(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return U(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),n=i(70283),s=i(98250),o=i(96593),a=i(27446);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(889),s=r(i(49411)),o=r(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),E=i(84593),T=i(21084),x=i(98250),D=i(95725),k=i(76531),C=i(7162),O=i(76474),I=i(19658),L=i(2023),F=i(55568),A=i(43414),R=i(13378),N=i(14889),j=i(91464),B=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Z=i(91854),Y=i(54988),X=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),ne=i(45023),se=(0,a.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const ae=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,F.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=ae();return e.ended?ae.refresh():e}function ue(e=!1){return(0,d.map)(ae.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(ae.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,B.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,j.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),n=await e.sidecar(),s=(0,X.isImageMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,X.isVideoMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||o||a;return se().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function pe(e,i=!0){const r=x.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void se().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;se().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,X.normalizeMimetype),...n},a=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(n))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(r.History)),(0,L.assignNullishFields)(o.original,(0,f.pick)(o,...(0,f.keys)(n))),(0,f.assignFields)(o,n),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,$.getInferredHistoricValues)(a,e),(0,L.assignNullishFields)(o,o.inferred),o.Rotation=(0,Q.orientationToRotation)(o.Rotation),se().debug("readRawTags() final",{pf:r,inferred:o.inferred,pickedResult:(0,f.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,a);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=a?(0,Y.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Y.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,a);if(null==h)return void se().info("No capturedAt for "+e);!a&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};I.isTest&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,L.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[n,s]of(0,f.entries)(t)){const t=await me(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=x.PosixFile.for(t),n=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:n}),await le().write(r.nativePath,n,await fe(r)),A.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),oe&&(r.__instance=(0,O.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(87748),a=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,r=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[o])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,h.toS)(n)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}r.push([o,(0,l.gt0)(a)?a:u])}var n;return S(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),o=n(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),s=_(i);if(null==r||null==s||e===i)return;const o=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=r[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(h.toS),a=(0,u.values)(i).map(h.toS);if((0,n.includesAny)(o,a))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),n=i(82798),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),n=i(39938),s=i(75556),o=i(61570),a=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),n=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),n=i(4866),s=i(11944),o=i(59694),a=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),E=i(43414),T=i(96593);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function L(e,i,r){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,T.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,o.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const r=O(e);(0,a.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=x(t.Actions.infer,r),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),L(i,n,s)},t.ensureHistoryRecords=L},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(9160)),s=i(889),o=i(4866),a=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,o.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,l.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),o=(0,d.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,d.normalizeZone)(o);if(null!=a)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),n=i(11944),s=i(39938),o=i(38625),a=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(66776),a=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,n.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),n=i(39938),s=i(66776),o=i(61570),a=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,n.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),n=i(82798),s=i(39607),o=i(71923),a=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),n=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,r.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),n=i(75556),s=i(43414);function o(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),n=i(39938),s=i(66776),o=i(21084),a=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),n=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(r.length)),l=s(i.slice(r.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),n=i(39938),s=i(88491),o=i(57743),a=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,r,await(0,h.rawInfo)(e));const s=b(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const n=(0,o.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),n=i(42748),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),E=i(98250),T=i(75123),x=i(95725),D=i(9483),k=i(43414),C=i(96879),O=i(69301),I=i(65642),L=i(96593),F=i(17310),A=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),j=7;async function B(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,A.extractMakeAndModel)(await(0,L.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await B(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(F.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,o.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await B(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,a.sortBy)(i,(e=>(0,O.bname)(e))),n=(0,x.findFileIndex)(e,r);if(n<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(n-2*t,n),r.slice(n+1,n+1+2*t)],c=[],d=[];for(;(0,o.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,o.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await B(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,j);for(const t of e){const e=await(0,L.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(66776),a=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,a.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,a.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,o.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),n=i(39938),s=i(61570),o=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,o.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),n=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,a.orElse)(n,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(E(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:M(a,!1)),r}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),n=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),n=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),n=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?o.join(t,...n):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),n=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),n=i(39036);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),n=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),n=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),n=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await L()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function L(){const e=(0,n.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(I)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=L},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),E=i(62255),T=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,T.mountpointsTtlMs)(),(()=>x().warn("gioVolumes(): timed out after "+T.mountpointsTtlMs+"ms")),(e=>x().log((0,n.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),n=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),n=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),n=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),n=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),E=i(51053),T=i(43414),x=i(39206),D=i(36736),k=i(62255),C=i(49829),O=i(10609),I=i(53719),L=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function F(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){F(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(F),T.Settings.scanPaths.watchLater(F),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return L().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(L().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),F()})),T.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,r.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),n=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=M,t=_,i=E){if(g.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=T,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),n=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),n=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),n=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),n=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await T(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=E,t.readUuidFile_=T,t.readVolumeUUID=x},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(70612)),s=r(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),E=i(14889),T=i(91464),x=i(46852),D=i(37121),k=i(1629),C=i(14195),O=i(42648),I=i(29405),L=i(20902),F=i(17875),A=i(79141),R=(i(79015),i(77390)),N=i(19653),j=i(3955),B=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Z=i(55412),Y=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),ne=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=n.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Z.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Z.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:se}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,N.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const n=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return ne().debug("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function ge(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,U.friendlyname)(e);return(0,x.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Z.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,F.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,F.onError)("Timed out getting local volume metadata")));if(null==e)return void ne().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,F.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>q.isWin?(0,g.opt)((0,L.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),n=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),n=i(11944),s=i(39938),o=i(49049),a=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,a.toURI)(e),l=i.scheme===o.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===o.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),n=i(11944),s=i(75556),o=i(48652),a=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,a.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,o.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),n=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),n=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let n=!1;function s(){n&&(n=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return n},t.pause=function(e=!0){!1===e?s():n||(n=!0,(0,r.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),n=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),n.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=S();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,w());return t=(0,o.clamp)(1,n,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),n=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),n=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),n=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),n=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(17954),a=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,o.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,o.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,a.toS)(e)+"```"},t.b=function(e){return"**"+(0,a.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,a.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),n=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),n=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),n=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),n=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),n=i(33714),s=i(17078);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),n=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,n.isFunction)(e)&&(0,n.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of a){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),n=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),n=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),n=i(38625),s=i(61570),o=i(61715),a=i(84253);t.HealthCheckSections=(0,a.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,a.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&o.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),n=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),n=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),n=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=n.length;(0,r.filterInPlace)(n,(t=>e(i,t))),t=t||s!==n.length,0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),n=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,n){return!(null==n||!l(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,n.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function T(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),n=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),n=i(23175),s=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),n=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),n=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),n=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),n=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),n=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),n=i(61570),s=i(90957),o=i(21669);async function a(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{r&&(0,n.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,n=!0){const s=await a(e,i,n);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,r=!0){const n=i-Date.now();return n<=0?t.Timeout:a(e,n,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return l(e,n,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:n=!0}){const o=await a(e,i,n);return o===t.Timeout?(0,s.tot)(r):o}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),n=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),n=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=h[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,n)}t.isChrome=l,t.isSafari=function(e){return a(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),n=i(39938),s=i(87748),o=i(75556),a=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,o.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,a.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),n=i(11448),s=i(75556),o=i(33912),a=i(82669);function l(e,i){const r=(0,a.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,a.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(o.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),n=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),n=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},57567:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainService=void 0;const d=c(i(97742)),h=i(4866),f=i(7162),m=i(97198),p=i(34996),g=i(36079),y=i(28807),v=i(91641),w=i(95557),S=i(4691),b=i(2126),P=i(46027),M=i(95237),_=i(53525),E=i(49379),T=i(17875),x=i(56958),D=i(79015),k=i(98462),C=i(13699),O=i(90524),I=i(47858),L=i(43414),F=i(82041),A=i(19209),R=i(36297),N=c(i(35280)),j=i(67220),B=i(39938),z=i(38625),V=i(88491),W=i(87748),U=i(66776),H=i(75556),q=i(61570),G=i(82798),$=i(20990),J=i(47707);class K{constructor(){r.add(this),this.start=Date.now(),n.set(this,(0,h.lazy)((()=>(0,f.mkLogger)("MainService")))),this.httpPort=new p.Deferred("MainService.httpPort"),this.libraryDir=new p.Deferred("MainService.libraryDir"),s.set(this,void 0),o.set(this,void 0),this.setup=(0,h.lazy)((async()=>{l(this,s,await M.ChildService.mk_("web",{onStdout:e=>this.onWebout("stdout",e),onStderr:e=>this.onWebout("stderr",e),onData:e=>this.onWebData(e),onRestartPaused:()=>(0,b.exit)({reason:"Too many web service fatal errors",status:13})}),"f"),await(0,B.mapNotBlank)(L.Settings.pidFile.value,(async e=>{const t=k.BaseFile.for(e);u(this,n,"f").call(this).info("Writing to pidfile "+t,{pid:d.default.pid}),await t.writeText_((0,G.toS)(d.default.pid)),new w.EndableWrapper("remove pidfile",(()=>t.unlink()),v.EndableRanks.postdb)})),await this.service.ready;try{await(0,C.externalDirectoryCheck)()}catch(e){u(this,n,"f").call(this).warn("Failed to check external directory permissions",{error:e})}if(L.Settings.startPaused.valueOrDefault&&(u(this,n,"f").call(this).info("Settings.startPaused: pausing on startup."),await(0,x.broadcastPause)()),this.service.setInputHandler("--restart-sync",(()=>this.restartSync(!1))),this.service.setInputHandler(O.HealthCheckCommand,(()=>u(this,r,"m",a).call(this))),null==u(this,s,"f"))return(0,T.onError)("Failed to start webservice"+_.FatalErrorFlag);(0,D.ee)().on("resume",(()=>this.onResume())),this.httpPort.promise.then((e=>{const t=(0,N.default)(e),i=(1===t.length?" ":"\n - ")+t.map((e=>`${e}`)).join("\n - ");(0,m.consoleLog)(`PhotoStructure is ready:${i}`),L.Settings.exposeNetworkWithoutAuth.valueOrDefault||(0,m.consoleLog)("See https://photostructure.com/faq/remote-access/ to enable non-localhost access.")})),this.libraryDir.promise.then((e=>{(0,m.consoleLog)(`Your library is at <${A.URI.file(e)}>`)})),new w.EndableWrapper("shutdown notice",(()=>(0,m.consoleLog)("\nShutting down PhotoStructure...")),v.EndableRanks.first),(0,H.gt0)(L.Settings.healthCheckIntervalMs.valueOrDefault)&&new y.EndableInterval({name:"webSyncHealthChecks",intervalMs:L.Settings.healthCheckIntervalMs.valueOrDefault,callback:()=>u(this,r,"m",a).call(this)})})),this.service=new $.Service({name:"main"}),this.setup(),(0,P.setUnrefTimeout)((()=>{this.httpPort.isPending&&!(0,S.ending)()&&(0,m.consoleLog)("Please wait, setting up...")}),4*V.secondMs)}async webHealthCheck(){const e=this.httpPort.value;if(null!=e)try{const t=await(0,I.httping)("localhost",e,"/ping",3*V.secondMs);return!!R.HttpStatusIs.success(t)||(u(this,n,"f").call(this).warn("webHealthCheck(): web service returned "+t),!1)}catch(e){return u(this,n,"f").call(this).warn("webHealthCheck(): httping error: "+e),!1}else u(this,n,"f").call(this).info("webHealthCheck(): no-op, no http port set (web is starting up still)")}onWebout(e,t){return u(this,n,"f").call(this).info("onWebout",{pipe:e,error:t}),t??(t=""),/EADDRINUSE/i.test(t)||t.includes(_.WebFatalErrorFlag)||(0,E.isFatalError)(t)?((0,b.exit)({status:1,reason:"Web service error",error:t}),!0):(this.onWebData((0,W.parseJSON)(t)),!1)}async onWebData(e){(0,B.blank)(e)||(u(this,n,"f").call(this).info("onWebData",{input:e}),(0,U.map)(e[L.Settings.httpPort.key],(e=>{u(this,n,"f").call(this).info("Got HTTP port number from web service:"+e),L.Settings.httpPort.envValue=e,this.httpPort.maybeResolve(e)})),(0,z.mapBoolean)(e.pause,(e=>e?(0,j.pause)():(0,j.resume)())),await(0,z.mapTrue)(e.shutdown,(()=>(0,b.exit)({reason:"shutdown requested",status:0}))),await(0,z.mapTrue)(e.shutdownSync,(()=>this.shutdownSync())),(0,z.isTrue)(e.forceRestartSync)?await this.forceRestartSync():(0,z.isTrue)(e.restartSync)&&await this.restartSync(!1))}async shutdownSync(){const e=u(this,o,"f");return l(this,o,void 0,"f"),u(this,n,"f").call(this).info("shutdownSync()",{syncWasDefined:null!=e}),(0,g.end)(e)}async rebuildLibrary(){const e=u(this,o,"f")?.write("--force-rebuild-library");return null==e?u(this,n,"f").call(this).throw("Cannot schedule library rebuild: no sync!"):!1===e?u(this,n,"f").call(this).throw("Cannot schedule library rebuild: sync process is not writable!"):u(this,n,"f").call(this).info("Scheduled library rebuild")}async forceRestartSync(){return this.restartSync(!0)}async restartSync(e){const t=(0,f.mkLogger)("MainService.restartSync()");if((0,S.ending)())return void t.info("ending, no-op");const i=u(this,o,"f");if(t.info("priorSync",(0,U.map)(i,(e=>(0,q.pick)(e,"pid","name")))),await(0,g.end)(i),l(this,o,void 0,"f"),await(0,F.readSystemSettings)(),!F.libraryHasSettings.refresh())return void t.info("restartSync(): no library settings",{libraryDir:L.Settings.libraryDir.value});e&&await(0,J.rmStatDbDirs)();const r=l(this,o,await M.ChildService.mk_("sync"),"f");t.info("Started sync",(0,U.map)(r,(e=>(0,q.pick)(e,"pid","name"))))}async onResume(){null==u(this,o,"f")&&!0===await this.webHealthCheck()&&(u(this,n,"f").call(this).info("onResume(): starting sync."),await this.restartSync(!1))}}t.MainService=K,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){!1===await this.webHealthCheck()?await u(this,s,"f").restart():u(this,s,"f").runHealthCheck(),u(this,o,"f")?.runHealthCheck()},K.instance=(0,h.lazy)((()=>new K))},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),n=i(20902),s=i(94845),o=i(43414);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,s.isPacked)()&&!0===o.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const a=s(i(9856)),l=o(i(70612)),u=o(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),S=i(91641),b=i(95557),P=i(4691),M=i(52289),_=i(10408),E=i(27519),T=i(49379),x=i(17875),D=i(79015),k=i(12737),C=i(49857),O=i(7157),I=i(85352),L=i(9483),F=i(15203),A=i(51053),R=i(11944),N=i(39938),j=i(88491),B=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),H=i(82798),q=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,q.sentryEnabled)()&&null!=e&&!0!==(0,T.isDoNotSendError)(e)&&a.captureException(e)}t.installSentry=async function(e){try{return!!(0,q.sentryEnabled)()&&(a.init({dsn:A.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,x.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:A.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,q.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(E.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,T.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(E.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new b.EndableWrapper("EventFilter",(()=>this.end()),S.EndableRanks.first)}end(){return(0,V.map)(a.getCurrentHub().getClient(),(e=>e.close(5*j.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,H.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,F.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/j.secondMs,...e}}async function Q(){await(0,B.delay)(3*I.DefaultLogFlushMs);const e=await(0,O.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/j.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[L.LogLevels.fatal,"fatal"],[L.LogLevels.error,"error"],[L.LogLevels.warn,"warning"],[L.LogLevels.info,"info"],[L.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),S=i(7162),b=i(33148),P=i(55568),M=i(25516),_=i(38307),E=i(42041),T=i(95557),x=i(4691),D=i(2126),k=i(7383),C=i(70259),O=i(24905),I=i(44731),L=i(20902),F=i(10408),A=i(53525),R=i(49379),N=i(17875),j=i(79141),B=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),H=i(27644),q=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Z=i(39938),Y=i(88491),X=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{k.PromiseTimer.instance(),(0,B.ee)().on("resume",(()=>(0,J.resume)())),(0,B.ee)().on("pause",(()=>(0,J.pause)())),(0,B.ee)().on("exit",(()=>(0,D.exit)({reason:"exit() event",status:0})))}));class ne extends T.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,new Q.Latch),o.set(this,!1),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,n,(0,S.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,s,"f").promise}get isReady(){return m(this,s,"f").isResolved()}setInputHandler(e,t){m(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ne,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Z.mapNotBlank)((0,L.getEnv)("PS_FATAL_"+this.name),(e=>{throw new j.WrappedError(e,{fatal:!0})})),(0,Z.mapNotBlank)((0,L.getEnv)("PS_CRASH_"+this.name),(e=>{(0,X.later)((()=>{throw new j.WrappedError(e)}),5*Y.secondMs)})),(0,b.setProcessTitle)(),(0,P.isMainService)()&&await(0,H.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,x.ending)()?m(this,s,"f").reject():m(this,s,"f").resolve()}catch(e){console.error((0,F.errorToS)(e)),m(this,s,"f").reject((0,te.toErr)(e)),(0,D.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,F.errorToS)(e),A.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:E.version}))),this.setInputHandler(O.ChildServiceExitCommand,(()=>(0,X.later)((()=>(0,D.exit)({reason:O.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,n,"f").debug("onLine()",{line:e,ending:m(this,o,"f")||(0,x.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,a,"f").get(t);null==i?(m(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,n,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),n=i(7162),s=i(93813),o=i(29731),a=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,n.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function S(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:s.AssetVersion,AssetFileVersion:s.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,o.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),n=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(n.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+n),n):n}async function b(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=S,t.vacuumStatDbDirs=async function(){const e=await S();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(a.SqliteBase).mtimeMs()]));(null==i||ie.option("-p, --pidfile PIDFILE","Write a pidfile of the main process.").option("--stop","Shutdown daemonized PhotoStructure. Requires --pidfile").option("-d, --daemon","Run PhotoStructure as a daemon. Enabled by default when --pidfile is provided."),afterParse:async e=>{if((0,h.mapNotBlank)(e.pidfile,(e=>c.Settings.pidFile.envValue=e)),(0,f.isTrue)(e.stop)){if(!c.Settings.pidFile.hasValue()&&(await(0,d.readSystemSettings)(),!c.Settings.pidFile.hasValue()))return console.error("--stop requires --pidfile to be set."),o.default.exit(1);const e=u.BaseFile.for(c.Settings.pidFile.value);if(await e.notExists())return console.error("Pidfile "+e+" does not exist."),o.default.exit(1);const t=(0,m.toInt)(await e.readTextFile());return(0,m.gt0)(t)?(0,n.pidExists)(t)?(await(0,a.killPid)(t),o.default.exit(0)):(console.error("Pid "+t+" does not exist."),o.default.exit(1)):(console.error("Pidfile "+e+" is invalid."),o.default.exit(1))}if(!(0,f.isTrue)(o.default.env.__is_daemon)&&((0,f.isTrue)(e.daemon)||c.Settings.pidFile.hasValue())){const e=o.default.argv.findIndex((e=>!e.includes("npx")&&!e.includes("node"))),t=o.default.argv.slice(-1===e?0:e),i=process.execPath,r={...(0,l.childEnv)(),__is_daemon:"1"},n=(0,s.spawn)(i,t,{env:r,detached:!0,shell:!0});return n.unref(),console.log("Daemonized PhotoStructure.",{pid:n.pid,args:t}),o.default.exit(0)}}}},51731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(43414),n=i(38625);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,n.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),n=i(85297),s=i(43414),o=i(38625);function a(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(a()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return a()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),a()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,o.isTrue)(e.error),i=(0,o.isTrue)(e.warn),r=(0,o.isTrue)(e.info)||(0,o.isTrue)(e.verbose)||(0,o.isTrue)(e.v),l=(0,o.isTrue)(e.debug),u=(0,o.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,o.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,a()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},50763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(23830),n=i(38625);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,n.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},38381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PauseSyncArg=void 0;const r=i(43414),n=i(38625);t.PauseSyncArg={beforeParse:e=>e.option("--pauseSync","Pause sync processing until manually resumed via the system tray or nav menu."),afterParse:e=>{(0,n.isTrue)(e.pauseSync)&&(r.Settings.startPaused.envValue=!0)}}},75965:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MainArgs=void 0;try{i(34261).install()}catch{}const r=i(37980),n=i(37445),s=i(43414),o=i(38625),a=i(7127),l=i(57567),u=i(44),c=i(51731),d=i(92045),h=i(50763),f=i(38381);t.MainArgs={beforeParse:e=>e.option("--quiet","Don't emit lifecycle messages to stdout from the main service."),afterParse:e=>{(0,o.isTrue)(e.quiet)&&(s.Settings.quiet.tmpValue=!0)}},async function(){try{await new r.CLI(a.ServiceNames.main).add(t.MainArgs,c.ExposeArg,f.PauseSyncArg,u.DaemonArgs,h.NoFilterArg,n.WriteSettingsArg,d.LogArgs).parse(),new l.MainService}catch(e){console.error("Failed to start:")}}()},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},5712:e=>{"use strict";e.exports=require("batch-cluster")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},42748:e=>{"use strict";e.exports=require("luxon")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},88849:e=>{"use strict";e.exports=require("node:http")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(75965);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/photostructure.js b/bin/photostructure.js index 85c2584..b292f17 100755 --- a/bin/photostructure.js +++ b/bin/photostructure.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function C(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await C(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),_=i(51053),M=i(43414),E=i(53719);class x extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=x,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(_.isWin?3:1)*o.minuteMs,maxTasksPerProcess:M.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:M.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:M.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?M():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function M(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),_=i(4691),M=i(46852),E=i(46027),x=i(4586),T=i(17875),C=i(98462),D=i(25015),k=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,D.isJsonExt)(t)&&(0,k.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,k.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,M.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,x.configDir)(),(e=>new j(C.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:R)).filter((e=>x(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function C(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=x,t.ps=async function(){const e=await(_.isWin?async function(){if(M.PowerShell.instance().ended)return A();const e=await M.PowerShell.instance().executeJsonToA([D,k].join(" "));return null==e?A():C(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(x),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const D="Get-Process",k="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return A(e);const t=[D,"-Id",O(e),"-ErrorAction SilentlyContinue",k].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>C(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function C(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=C,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const M=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),_=i(75556),M=i(61570),E=i(26588),x=i(46234),T=i(21669),C=i(7162),D=i(49379),k=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,C.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,_.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,C.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function _(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=_,t.rejected=async function(e){return!await _(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),n=t();return M(e,Date.now()-i),n},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>_(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const _=["HOME","LANG","USER"],M=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?_:M),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function x(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=x,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:C({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function C({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...x(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=C},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),_=i(34996),M=i(46027),E=i(49379),x=i(79141),T=i(83837),C=i(95976),D=i(10347),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,M.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,D.spawnOptions)(n);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new _.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),k().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const M=y.join("");(0,l.notBlank)(M)&&v.push(new Error(M)),!n&&(0,a.isNotEmpty)(v)&&k().warn(m+" resulted in errors:",v);const C=i.isIgnorableError??E.isIgnorableError,D=v.filter((e=>!0!==C(e)));if(D.length>0)throw 1===D.length?D[0]:new x.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:M}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,D.spawnOptions)(n);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),_=i(53525),M=i(17875),E=i(79141),x=i(45512),T=i(7162),C=i(75405),D=i(43414),k=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,M.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,C.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),_=i(95699),M=i(58676),E=i(51510),x=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function C(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function D(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...C()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...C()),i}t.tmpCacheDirs=C,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:C(),desc:"tmp"})},t.cacheDirs=D,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:D(),desc:"cache"})));const k=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{k();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await M(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),_=i(59694),M=i(38625),E=i(88491),x=i(43383),T=i(24603),C=i(16475),D=i(1429),k=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),j=i(70283),B=i(55568),V=i(14889),z=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),J=i(91641),$=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,z.StartTs):n}function Se(e){const t=(0,_.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,k.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,M.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,k.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,D.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,D.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,_.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,k.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,x.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,C.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),_=i(11944),M=i(92585),E=i(39938),x=i(88491),T=i(24603),C=i(1429),D=i(87748),k=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),j=i(13779),B=i(34996),V=i(46852),z=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),J=i(7162),$=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,C.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,z.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,z.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,k.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*x.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new M(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),_=b(i(44470)),M=i(92332),E=i(11944),x=i(37609),T=i(88491),C=i(24603),D=i(19067),k=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),j=i(91641),B=i(95557),V=i(4691),z=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,z.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,C.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,k.map)(w(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),_=i(28807),M=i(91641),E=i(17354),x=i(79015),T=i(3955),C=i(8177),D=i(43414),k=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends _.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,C.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,C.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends _.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:M.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,x.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),D.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:D.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,k.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const _=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function M(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&_().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return x(e,i,t);const n=await Promise.race([E(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function x(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&x(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,M)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=M},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function _(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return D(e).some(_)},t.isNotHiddenPosixPath=function(e){return D(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function x(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function C(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function D(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function k(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return C(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return C(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return C(w.toNativePath_,e,t)},t.toPathnames=D,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&D(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:D(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=D(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return D(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return D(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=k,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(k(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),_=i(19067),M=i(66776),E=i(75556),x=i(61570),T=i(20636),C=i(49049),D=i(17078),k=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),j=i(69317),B=i(14195),V=i(53525),z=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),J=i(43414),$=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===C.PS_LIBRARY_SCHEME?1:t.scheme===C.PS_LOCAL_FILE_SCHEME?2:t.scheme===C.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const _=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=x(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):x(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function _(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=_,t.statEql=function(e,t){return null==_(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),_=i(51053),M=i(43414),E=i(53719),x="{ready}",T=" | ConvertTo-Json -Compress";function C(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=C,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+C(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,r.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),_=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],_.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],_.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],_.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),_=i(27387),M=i(29393),E=i(94794),x=i(7560),T=i(45005),C=i(20902),D=i(6565),k=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),j=i(98788),B=i(61659),V=i(40185),z=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),J=i(1440),$=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:D.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:k.CropStrategies.attention,strEnum:k.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:z.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,C.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?M:_;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:_(a,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=E;const C=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(C)?e.replace(C,(e=>T(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),_=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(M)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function C(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(C)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),_=i(7903),M=i(55412),E=i(62255),x=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await C(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,x.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+x.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const C=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),_=i(95725),M=i(76531),E=i(51053),x=i(43414),T=i(39206),C=i(36736),D=i(62255),k=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{x.Settings.libraryDir.watchLater(L),x.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,D.maybeWatchProcMounts)(),await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=x.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||x.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,_.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),L()})),x.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=M,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=x,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(_)?new h.FsWatcher({target:_,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+_),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),_=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function M(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await x(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>_.clear())),w.mountpoints.watchLater((()=>_.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(M(e))return;if((0,o.isFalse)(e.ok))return;const t=await _().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=M,t.toVolumeUUID=E,t.readUuidFile_=x,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),_=i(55568),M=i(91710),E=i(14889),x=i(91464),T=i(46852),C=i(37121),D=i(1629),k=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),j=i(3955),B=i(98250),V=i(95725),z=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),J=i(47044),$=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,x.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,_.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,x.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,x.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,x.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,_.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,x.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function _(e,t){return l(e)?t(e):void 0}function M(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return M(e*i)/i}function x(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=_,t.map2Numeric=function(e,t,i){return _(e,(e=>_(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=M,t.toFixed=function(e,t){try{return _(e,(e=>M(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-M(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?M(e/n)*n:M(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=x,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return x(0,100,S(t)?M(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},87978:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(7304),s=n(i(87561)),o=n(i(49411)),a=i(97742),l=i(42041),u=i(79682),c=i(38507);function d(e){for(const t of["bin",__dirname]){const i=o.default.join(t,e);if(s.default.existsSync(i))return i}return console.error("failed to find command "+e),e}r.program.version(l.version),r.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,c.verifyUidGid)(),(0,u.addFooter)(r.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:d("main.js")}).command("info",u.CliDesc.info,{executableFile:d("info.js")}).command("list",u.CliDesc.list,{executableFile:d("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:d("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:d("logtail.js")}).command("web",u.CliDesc.web,{executableFile:d("web.js")}).command("sync",u.CliDesc.sync,{executableFile:d("sync.js")}).parse(a.argv)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(87978);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function C(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await C(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),_=i(51053),M=i(43414),E=i(53719);class x extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=x,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(_.isWin?3:1)*o.minuteMs,maxTasksPerProcess:M.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:M.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:M.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?M():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function M(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),_=i(4691),M=i(46852),E=i(46027),x=i(4586),T=i(17875),C=i(98462),D=i(25015),k=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,D.isJsonExt)(t)&&(0,k.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,k.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,M.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,x.configDir)(),(e=>new j(C.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:R)).filter((e=>x(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function C(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=x,t.ps=async function(){const e=await(_.isWin?async function(){if(M.PowerShell.instance().ended)return A();const e=await M.PowerShell.instance().executeJsonToA([D,k].join(" "));return null==e?A():C(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(x),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const D="Get-Process",k="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return A(e);const t=[D,"-Id",O(e),"-ErrorAction SilentlyContinue",k].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>C(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function C(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=C,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const M=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),_=i(75556),M=i(61570),E=i(26588),x=i(46234),T=i(21669),C=i(7162),D=i(49379),k=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,C.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,_.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,C.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function _(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=_,t.rejected=async function(e){return!await _(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),n=t();return M(e,Date.now()-i),n},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>_(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const _=["HOME","LANG","USER"],M=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?_:M),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function x(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=x,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:C({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function C({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...x(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=C},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),_=i(34996),M=i(46027),E=i(49379),x=i(79141),T=i(83837),C=i(95976),D=i(10347),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,M.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,D.spawnOptions)(n);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new _.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),k().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const M=y.join("");(0,l.notBlank)(M)&&v.push(new Error(M)),!n&&(0,a.isNotEmpty)(v)&&k().warn(m+" resulted in errors:",v);const C=i.isIgnorableError??E.isIgnorableError,D=v.filter((e=>!0!==C(e)));if(D.length>0)throw 1===D.length?D[0]:new x.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:M}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,D.spawnOptions)(n);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),_=i(53525),M=i(17875),E=i(79141),x=i(45512),T=i(7162),C=i(75405),D=i(43414),k=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,M.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,C.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),_=i(95699),M=i(58676),E=i(51510),x=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function C(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function D(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...C()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...C()),i}t.tmpCacheDirs=C,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:C(),desc:"tmp"})},t.cacheDirs=D,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:D(),desc:"cache"})));const k=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{k();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await M(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),_=i(59694),M=i(38625),E=i(88491),x=i(43383),T=i(24603),C=i(16475),D=i(1429),k=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),j=i(70283),B=i(55568),V=i(14889),z=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),J=i(91641),$=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,z.StartTs):n}function Se(e){const t=(0,_.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,k.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,M.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,k.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,D.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,D.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,_.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,k.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,x.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,C.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),_=i(11944),M=i(92585),E=i(39938),x=i(88491),T=i(24603),C=i(1429),D=i(87748),k=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),j=i(13779),B=i(34996),V=i(46852),z=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),J=i(7162),$=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,C.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,z.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,z.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,k.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*x.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new M(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),_=b(i(44470)),M=i(92332),E=i(11944),x=i(37609),T=i(88491),C=i(24603),D=i(19067),k=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),j=i(91641),B=i(95557),V=i(4691),z=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,z.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,C.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,k.map)(w(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),_=i(28807),M=i(91641),E=i(17354),x=i(79015),T=i(3955),C=i(8177),D=i(43414),k=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends _.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,C.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,C.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends _.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:M.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,x.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),D.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:D.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,k.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const _=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function M(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&_().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return x(e,i,t);const n=await Promise.race([E(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function x(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&x(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,M)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=M},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function _(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return D(e).some(_)},t.isNotHiddenPosixPath=function(e){return D(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function x(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function C(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function D(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function k(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return C(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return C(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return C(w.toNativePath_,e,t)},t.toPathnames=D,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&D(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:D(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=D(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return D(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return D(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=k,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(k(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),_=i(19067),M=i(66776),E=i(75556),x=i(61570),T=i(20636),C=i(49049),D=i(17078),k=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),j=i(69317),B=i(14195),V=i(53525),z=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),J=i(43414),$=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===C.PS_LIBRARY_SCHEME?1:t.scheme===C.PS_LOCAL_FILE_SCHEME?2:t.scheme===C.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const _=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=x(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):x(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function _(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=_,t.statEql=function(e,t){return null==_(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),_=i(51053),M=i(43414),E=i(53719),x="{ready}",T=" | ConvertTo-Json -Compress";function C(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=C,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+C(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,r.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),_=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],_.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],_.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],_.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),_=i(27387),M=i(29393),E=i(94794),x=i(7560),T=i(45005),C=i(20902),D=i(6565),k=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),j=i(98788),B=i(61659),V=i(40185),z=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),J=i(1440),$=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:D.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:k.CropStrategies.attention,strEnum:k.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:z.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,C.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?M:_;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:_(a,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=E;const C=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(C)?e.replace(C,(e=>T(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),_=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(M)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function C(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(C)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),_=i(7903),M=i(55412),E=i(62255),x=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await C(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,x.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+x.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const C=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),_=i(95725),M=i(76531),E=i(51053),x=i(43414),T=i(39206),C=i(36736),D=i(62255),k=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{x.Settings.libraryDir.watchLater(L),x.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,D.maybeWatchProcMounts)(),await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=x.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||x.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,_.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),L()})),x.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=M,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=x,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(_)?new h.FsWatcher({target:_,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+_),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),_=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function M(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await x(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>_.clear())),w.mountpoints.watchLater((()=>_.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(M(e))return;if((0,o.isFalse)(e.ok))return;const t=await _().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=M,t.toVolumeUUID=E,t.readUuidFile_=x,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),_=i(55568),M=i(91710),E=i(14889),x=i(91464),T=i(46852),C=i(37121),D=i(1629),k=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),j=i(3955),B=i(98250),V=i(95725),z=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),J=i(47044),$=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,x.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,_.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,x.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,x.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,x.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,_.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,x.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function _(e,t){return l(e)?t(e):void 0}function M(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return M(e*i)/i}function x(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=_,t.map2Numeric=function(e,t,i){return _(e,(e=>_(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=M,t.toFixed=function(e,t){try{return _(e,(e=>M(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-M(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?M(e/n)*n:M(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=x,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return x(0,100,S(t)?M(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},87978:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(7304),s=n(i(87561)),o=n(i(49411)),a=i(97742),l=i(42041),u=i(79682),c=i(38507);function d(e){for(const t of["bin",__dirname]){const i=o.default.join(t,e);if(s.default.existsSync(i))return i}return console.error("failed to find command "+e),e}r.program.version(l.version),r.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,c.verifyUidGid)(),(0,u.addFooter)(r.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:d("main.js")}).command("info",u.CliDesc.info,{executableFile:d("info.js")}).command("list",u.CliDesc.list,{executableFile:d("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:d("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:d("logtail.js")}).command("web",u.CliDesc.web,{executableFile:d("web.js")}).command("sync",u.CliDesc.sync,{executableFile:d("sync.js")}).parse(a.argv)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(87978);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/sync.js b/bin/sync.js index 6cf1986..c3a81ef 100755 --- a/bin/sync.js +++ b/bin/sync.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:s,PasetoNotSupported:r}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new s("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new r("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new r("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new s("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const s=i(79551);e.exports={decode:s}},77308:(e,t,i)=>{const s=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:r,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+s(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+s(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==r){if("string"!=typeof r)throw new TypeError("options.issuer must be a string");c.iss=r}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:s}=i(74485),r=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new s("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new s("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new s("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new s("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new s("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new s("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?r(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new s("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new s("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new s("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new s("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new s("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new s("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new s("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new s("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new s("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new s("missing iat claim");if(m+r(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const s=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(s(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const s=i(77308),r=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!r(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=s(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),s=Buffer.from(i,"base64"),r=2+(1&s[s.length-1]);return Buffer.concat([Buffer.alloc(1,r),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const s=i(39084),{PasetoInvalid:r}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,s,r,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return s?{payload:r,footer:a?.length?a:void 0,version:e,purpose:l}:r}const u=o(r);return n(i,u),s?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new r(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{s(o<=2),i=a(i),n=a(n)}catch{throw new r("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const s=i(6113),r=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=s,c=r.promisify(s.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>s.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,s)=>u[e]({name:"AES-CTR",counter:s,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:r.promisify(s.sign),verify:r.promisify(s.verify),"v1.local-encrypt":async function(e,t,i){const r="v1.local.",o=m(e,s.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(r,o,p,t),v=m(y,f);return a(r,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const s=e.subarray(0,32),r=e.subarray(-48),a=e.subarray(32,-48),u=s.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",s,a,t),v=m(g,p);if(!l(r,v))throw new o("decryption failed");const w=await y(a,f,s.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,r){const o="v3.local.",l=s.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,r),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,s){const r=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,r]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,r]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",r,u,t,s),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:s}=i(6113);let{isKeyObject:r}=i(35740);r||(r=e=>null!=e&&e instanceof s),e.exports=r},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:s}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new s("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,r=Buffer.allocUnsafe(8);return r.writeUInt32LE(t,4),r.writeUInt32LE(i,0),r}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const s=i.exec(e);if(!s)throw new TypeError(`invalid time period format ("${e}")`);const r=parseFloat(s[1]);switch(s[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*r);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*t);case"day":case"days":case"d":return Math.round(864e5*r);case"week":case"weeks":case"w":return Math.round(6048e5*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*r)}}},45018:(e,t,i)=>{const{encode:s}=i(87536);e.exports=function(e,t,...i){let r=`${e}${s(Buffer.concat(i))}`;return t.byteLength&&(r+=`.${s(t)}`),r}},97540:(e,t,i)=>{const s=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=s(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=s(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:s}=i(74485),{strict:r}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return r(n(t)),t}catch{throw new s("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:s}=i(45112),r=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=r(u,e,t,i,l),d=await s(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:s}=i(6113),r=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!r(t))try{t=s(t)}catch{}if(!r(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:s}=i(6113),r=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return s(r(e,i),r(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:s}=i(74485),{verify:r}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await r(i,p,l,m))throw new s("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const s=i(74485),r=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:r,V2:n,V3:a,V4:o,errors:s}},34089:(e,t,i)=>{const{"v1.local-decrypt":s}=i(45112),r=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=r(t)).export(),h=await s(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const s=i(25054),r=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=r(t);const u=s(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const s=i(54773),r=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:s,verify:r,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const s=i(6113),{promisify:r}=i(16464),{PasetoNotSupported:n}=i(74485),a=r(s.generateKeyPair),o=r(s.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:s,RSA_PSS_SALTLEN_DIGEST:r},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:s,saltLength:r})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:s,RSA_PSS_SALTLEN_DIGEST:r},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:s,saltLength:r});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const s=i(83985),r=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:s,verify:r,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const s=i(39084),r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(r.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:s}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(s).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=r.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return r.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),s.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=r.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),s.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=r.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const s=i(25054),r=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=r(e,a);t=o(t);const u=s(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const s=i(80094),{_checkPublicKey:r}=i(42421),{post:n}=i(97362),a=r.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:r=!1,...o}={}){t=a(t);const{m:l,footer:u}=await s("v2.public.",e,void 0,64,t);return n("v2",r,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":s}=i(45112),r=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=r(t);const f=n(u),m=t.export(),p=await s(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const s=i(25054),r=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=r(t);const d=s(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const s=i(38681),r=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:s,verify:r,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const s=i(6113),{promisify:r}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=r(s.generateKeyPair),u=r(s.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return s.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return s.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return s.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:s}=i(6113),r=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=r(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=s(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:s}=i(6113),r=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=r(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const s=i(54294),r=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:s,verify:r,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:s,_checkPublicKey:r,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:s,_checkPublicKey:r,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const s=i(25054),r=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=r(e,u),d=n(o);t=l(t);const h=s(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const s=i(42417),r=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=s(l),{m:d,footer:h}=await r("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const s=i(4866),r=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,s.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,s.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const s=i(11944),r=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=s.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,s.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,s.isEmpty)(e))return{index:-1,value:void 0};let r,n=-1;for(let s=0;se.slice(i,i+t)))}async function k(e,t){return(0,s.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const s=e[i];if(null!=s&&!0===await t(s))return s}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const s of e){i++;try{if(null!=s){const e=await t(s,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,s.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let s=i;s<=e.length-1;s++)if(t(e[s]))return s},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,s.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,s.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],s=[];let r=0;for(const n of e)(t(n,r++)?i:s).push(n);return[i,s]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,s.compact)((0,s.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const s=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,s.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const r=[];for(const n of D((0,s.compact)((0,f.toA)(e)),t))r.push(...(0,s.compact)(i(n)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const n of D((0,s.compact)((0,f.toA)(e)),t))r.push(...(0,s.compact)(await i(n)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,s)=>(0,d.tap)(t(e,s,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const s of e){const e=i.find((e=>e.some((e=>t(s,e)))));e?e.push(s):i.push([s])}return i},t.clusterEvery=function(e,t){const i=[];for(const s of e){const e=i.find((e=>e.every((e=>t(s,e)))));e?e.push(s):i.push([s])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const s of e){for(const e of i)if(null!=s&&await k(e,(e=>t(s,e)))){e.push(s);continue e}null!=s&&i.push([s])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[s],(e=>i(e,s))))return s}{const s=t+r;if(se+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=s(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const s=t;s.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),s.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),s.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),s.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),s.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),s.on("noTaskData",((e,i,s)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),s.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const s=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new s.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const s=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,s.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,s.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const s=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,s.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const s=i(97461);class r{constructor(e=[],t=s.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let s,r=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(n);null!=e&&(s=e,r=a)}}return s}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const s=i(21941);let r=!(0,s.noColor)();function n(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,s.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const s=i(59694),r=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,s.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,s.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,s.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[s,r]of this.m.entries()){const n=e(s);t.fill(n,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const s=i(4866),r=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,s.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,s.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const s=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,s.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const s=i(24603),r=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,s.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,s.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,s.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,s.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,s.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const s=i(39653),r=i(4866),n=i(98250);t.examples=(0,r.lazy)((()=>n.PosixFile.for((0,s.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const s=i(4866),r=i(40786),n=i(3955);t.examplesNativePath_=(0,s.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const s=i(47261),r=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[s.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,s.set(this,0),r.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,s,l(this,s,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,s,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,s,(a=l(this,s,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,s,(o=l(this,s,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,s,(i=l(this,s,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,s,0,"f"),u(this,r,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const s=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,s),(0,c.gt0)(this.opts.timeoutMs)&&s.setTimeout(this.opts.timeoutMs),s.promise.then((e=>{this.set(i,e)}),(e=>{var t,s;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(s=l(this,o,"f"),++s),"f")})),s.promise}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class s{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=s},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,s.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const s=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,s).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let s,o=0;for(;null!=(s=t.exec(this.headerRow));){const l=this.headerRow.substring(o,s.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:s.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(s.index,t.lastIndex),d=s.index+((0,c.indexOfNonSpace)(u)??0),h=s.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:s,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,s.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const s=i(66776),r=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,s.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,s]=p(e,t);return{lat:i,lon:s}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,s.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,s=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(s)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,s=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return s(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const s=i(4866);t.isSuspended=(0,s.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const s=i(93977),r=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,s.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const s=i(889),r=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(s.ExifDateTime,s.ExifDate,s.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,s.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),s.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,s,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,s=await t;if(!(0,l.eql)(i,s))for(const e of this.watchers)e(s);null!=this.ttlMs&&this.ttlMs>0&&void 0!==s&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,s.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,s.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const s=i(70612),r=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,s.arch)(),platform:(0,s.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const s=i(4866),r=i(74269),n=i(78109);t.rootLoggers=(0,s.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,s.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const s=i(11944),r=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,s.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,s.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,s.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,s]of e)t[i]=s;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,s])=>t(i,s)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const s=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const n=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,s.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,s.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const s=i(97742),r=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,s.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,s.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const s=i(38625);t.noColor=function(){return(0,s.toBoolean)(process.env.PS_LOG_COLOR)??(0,s.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=s(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const s=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=s&&s>0&&null!=r&&r>0?i(s,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),s=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,s,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let s=0;se/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,s.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,s.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let s=0;const r=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const s=i(11944),r=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[s,r]of(0,u.entries)(e)){const e=t(s,r);null!=e&&(i[s]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,s.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,s]of p(t))null==e[i]&&(e[i]=s);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,s]of(0,u.entries)(t))null==e[i]&&(e[i]=s);return e},t.pickMap=function(e,t,i){const s={};for(const r of t)s[r]=i(r,e[r]);return s},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const s={};let r=0;for(const n of(0,u.keys)(e))if(s[n]=t(n,e[n]),r++,(0,l.gt)(r,i))break;return s},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const s of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[s]=e(t[s]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,s)=>i.includes(t)?void 0:e(s,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,s.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const s=i(17718),r=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,s]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[s]}const x=(0,a.lazy)((()=>(0,s.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const s=i(5712),r=i(39784),n=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(s.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,s.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),n=s(i(17718)),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),E=i(4586),D=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),A=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),O=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),s=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(s)&&Math.abs(i-s){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))A().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,s=await this.pidfiles(),r=await this.pids(s??[]);if((0,l.isEmpty)(r))return A().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of s){const s=await r.readJson();if(null==s){A().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=s.pid;if(!(0,h.gt0)(l)){A().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:s,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(s,u)){A().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:s,pidEntry:u}),await r.unlink("debug"),n.push(s);continue}const c=(0,h.gt0)(s.timeoutMs)?s.startTime+s.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(s.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(A().info("killOldProcs(): killing",{reason:d,json:s}),a.push(N(l,i,!1)),n.push({...s,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const s=e.pid;if(!(0,h.gt0)(s))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,r.pidExists)(s)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),s=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),n={...e,cmd:s,startTime:r};return await i.writeJson_(n),A().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void A().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{A().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=s(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const s=i(9678),r=i(7162),n=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?s.SimpleShortAppName:s.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const r=s(i(97742)),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),b=i(46852),S=i(69317),P=i(9288),M=i(51053),_=i(71663),T=(0,n.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],A))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const A={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},O=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",O.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,A),s=(0,d.onlyReqValued)((0,p.parseFixed)(O,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return s.find((e=>e.pid===r.default.pid))||s.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),s}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...A,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const s=i(6231),r=i(3331);t.safeRandomChars=function({radix:e=s.TokenRadix,length:t}){return(0,r.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,r.decuss)((()=>(e?.radix??s.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const s=i(43947),r=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,s.delay)(1).then((()=>e))}return async function(...s){f=!0,m=Date.now()+(0,n.max_)(t,i);const r=d=new a.Deferred(c);(0,n.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...s))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const s=i(61570),r=i(82798);function n(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,s.pick)(r,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const s=[];for(const t of e)try{s.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{s.push(n(t))}const r=0===s.length?t.NothingRegExp:s.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",s=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,s||(s=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,r.toS)(t));return new RegExp(i,t??(s?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=s(i(70612)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const s=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:s,error:i}),s)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=s(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const s=i(39784);function r(e){return e instanceof Set?e:new Set((0,s.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,s.toA)(e.keys()).every((e=>t.has(e)))&&(0,s.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const s=i(7127),r=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=s.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const s=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,s.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const s=i(87748),r=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,s.stringify)(e))}){let o;const l=async i=>{const s=Date.now(),r=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-s),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const s=i(88491);t.ShortCommandTimeoutMs=7*s.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),r=this.valueOf(this.store[s]);if(e===r)return{found:!0,index:s};e>r?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,s.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const s=i(97742),r=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(s.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const s=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(s.stdout)}},38307:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=s(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:s}){if(null==s||(0,d.streamEnded)(s))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);s.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?s.write(u.FailStr+"\n"):s.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const s=String(e);return s+(0,l.padding)(i,t-s.length)},t.padReplace=function(e,t,i,s){return(0,c.strslice)(e,0,t)+(0,l.padding)(s,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,s=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,s);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const s=Math.min(Math.ceil(e.length/t),i??e.length)-1;return s<=0?[e]:[...(0,o.times)(s,(i=>e.slice(i*t,(i+1)*t))),e.slice(s*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const s=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,s)+e.substring(s+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:s}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const s=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(s.slice(-r.length),r,i)?s.slice(0,-r.length):s},t.gist=function(e,t=80,i=80){const s=(0,h.toS)(e),r=s.length-(t+i);return r<=0?s:s.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+s.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,s.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,s.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),s=e.toLowerCase(),r=t.indexOf(s);if(r>=0)return{index:r,match:s}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],s=[];let r,n=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(n,r.index)),s.push(e.substring(r.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,s.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,s.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let s=0;s4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const s of(0,d.toA)(e))if(null!=s&&!(0,n.blank)(s))for(const e of s.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const s=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>s.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const s=i(82798);function r(e){return(0,s.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,s.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,s.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=s(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,s=224){return i.encodeBuffer(o(e,s)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,s=224){return l(e,t,i,s)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const s=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,s.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let s=0,r="";for(let n=0;n=s&&(s=i.get(n,a),r=(0,l.substr)(e,n-s+1,s)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const s=e.normalize(),r=t.normalize();return e!==s||t!==r?y(s,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,s)=>i===t.charAt(s)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),s=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===s?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(s);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const n=Math.min((0,s.count)(e,(e=>e===i)),(0,s.count)(t,(e=>e===i)));(0,a.times)(n,(()=>r.push(i)))})),r}function S(e,t,i){const r=(0,s.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,s.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,s]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,s,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,s]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,s,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let s=Math.max(e.length,t.length);s>=0;s--){const r=(0,a.mapNumericOr)(e.charCodeAt(s),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(s),(e=>e),256),o=(0,a.clamp)(-256,256,r-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,s.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,s.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const s=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,s.stringify)((0,r.sortedKeys)(e))}},55646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const s=i(75556);class r{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,s.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=r},3917:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){s.add(this),this[c]="TTLMap",r.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,s,"m",u).call(this)),e),"f"),d(this,s,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,s,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,s,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,s,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,s,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,s,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,s,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,s,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,s,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){s.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,s,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,s,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,s,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,s,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,s,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,s,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,s,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,s,"m",n).call(this),[...this.delegate.keys()]}[(s=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,s,"m",r).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const s=i(4866),r=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,s.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=s(i(70612)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",s.set(this,new Map)}clear(){return a(this,s,"f").clear(),this}delete(e){return a(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,s,"f").delete(t)}get(e){const t=a(this,s,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,s,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,s,"f").get(e)?.deref();if(null!=i)return i;const r=t();return null!=r&&this.set(e,r),r}set(e,t){return a(this,s,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,s,"f").get(e)?.deref()}get size(){return a(this,i,"m",r).call(this),a(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries())null==i.deref()?a(e,s,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries()){const r=i.deref();null==r?a(e,s,"f").delete(t):yield r}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries()){const r=i.deref();null==r?a(e,s,"f").delete(t):yield[t,r]}}()}[(s=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,r=function(){for(const[e,t]of a(this,s,"f").entries())null==t.deref()&&a(this,s,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const s=i(88491),r=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*s.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+s.dayMs,e))).map((e=>new Date(e))).get()}},46080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const s=i(39784),r=i(13779),n=i(1440),a=i(43414),o=i(67654),l=i(92356);t.aggregateAssetFiles=async function(e){const t=(0,s.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?r.clusterSome:r.clusterEvery)(t,o.isSimilarAssetFile)}},67654:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(24603),o=i(66776),l=i(75556),u=i(61570),c=i(17078),d=i(84593),h=i(85563),f=i(7162),m=i(34928),p=i(72461),g=i(32148),y=i(43414),v=i(65642),w=i(74873),b=i(27446),S=(0,s.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,s=((e,t)=>[e,t])){const r=e[i],o=t[i];if((0,n.blank)(r)||(0,n.blank)(o)||(0,a.eql)(r,o))return;const[l,u]=s(r,o);return(0,a.eql)(l,u)||(0,a.eql)(r,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${r} โ‰  ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const s=(0,w.findInequalFields)(e[i],t[i]);return null==s?void 0:`Different ${i} (${s.aKey}:${s.aValue} โ‰  ${s.aKey}:${s.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const s=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(s!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:s,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),s=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,s,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:k});const x=(0,r.compact)((0,u.values)(k));if((0,r.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),s=(0,p.toImageHash)(i);if(null!=t&&null!=s){const e=(0,g.compareImageHashes)(t,s,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos โ‰  images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const s of i)if(s.id!==t?.id){const t=E(e,s);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const s=i(4866),r=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,s.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,s,r,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...s,...r,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const s=i.capturedAt.toAssetFileFields();return null==s?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...s,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,s.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const s=P.indexOf(t.scheme);if(null==s)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:s,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(r),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const s=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,s.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=s(i(92332)),n=i(75556);t.debounce=function(e,t){let i,s=[];const a=(0,n.gt0)(t)?(...n)=>{s=n,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...s)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),E=i(46234),D=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const s=i[e];if(s.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield s}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;s.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,s=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,s,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,s,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,r=A,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},47284:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const s=i(6314),r=i(95557);class n extends r.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new s.Latch}isDone(){return!this.doneLatch.isPending()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,s.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const s=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:s});try{await(0,o.thenOrTimeoutError)(i.end(),s,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,s.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,s,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),s.add(this),this.opts=e,r.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,s,"m",a).call(this);const h=()=>{u(this,s,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,s,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,n=new WeakMap,o=new WeakMap,s=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const s=i(84253);t.EndableRanks=(0,s.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,s.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,s,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,s,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,r,"f").call(this)}},s=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const s=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=s.isTest?e:e||r}},2126:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=s(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const s=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(s)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5685:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(89253),a=i(82798),o=i(59387),l=i(70259);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,s.set(this,new n.MultiMap),this.p=new l.Promises(e,t)}vacuum(){r(this,s,"f").filterInPlace(((e,t)=>!t.signal.aborted))}enqueue(e,t){for(const t of r(this,s,"f").get(e)??[])t.abort();this.vacuum();const i=new AbortController;return r(this,s,"f").add(e,i),this.p.serial((0,a.toS)(e),(()=>t(i)))}},s=new WeakMap},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,s)=>{t=e,i=s})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:s}){return new v(e,t,i,s)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),s.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,s,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,r,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,s,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,s,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,s=new WeakSet,u=async function(e,t){var i;const s=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===s&&h(this,a,i,"f"),d(this,o,"f")?.id===s&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,s,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const s=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new r.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,s.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,s.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const s=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:r):(n=!0,r=(0,s.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const s=i(11944),r=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,s.compact)(await e);return(0,s.isEmpty)(t)?[]:(0,s.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const n=[];for(const a of(0,s.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,s.compact)(await e);if((0,s.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=r?b.PermissivePromises:new b.Promises(i,(()=>r))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,s.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const s=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);s.push(...await P(i(e)))}return s},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,s.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,s.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:r,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:r,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:n}){return(await T({name:e,arr:(0,s.compact)(t),f:i,maxConcurrent:r,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),s=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,s)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let s,r=null;try{s=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??s)}catch{}if(null!=r)throw r;return s},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const s=await e;if(null==s)return;const r=await t;return null!=r?i(s,r):void 0},t.thenMapOr=async function(e,t,i){const s=await e;if(null==s)return i();const r=await t(s);return null==r?i():r},t.thenMap2Or=async function(e,t,i,s){const r=await e;if(null==r)return s();const n=await t;if(null==n)return s();const a=await i(r,n);return null==a?s():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const s of e){i++;try{if(null==s)continue;const e=await t(s,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const s=await T({name:e,arr:t,f:i});return(0,r.sortBy)(s,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const s=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-s)+"ms")),r);try{const r=await(0,c.tot)(t),n=Date.now()-s;return i?.(r,n),this.push(e,n),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-s),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),s=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...s])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,s.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),s=t();return _(e,Date.now()-i),s},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,s.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){s.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,r,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const n=d(this,s,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,s,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,s,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,l=function({name:e,l:t,payload:i,serialId:s}){const r=new P.Deferred(e,{payload:i,serialId:s});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},39506:function(e,t){"use strict";var i,s=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return r(this,i,s(this,i,"f").catch().then(e),"f")}},i=new WeakMap},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const s=i(41135),r=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,s.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,s.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const s=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,s.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,s.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const s=i(38625),r=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:s,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const s=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,n.delay)(s,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:s.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=s(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,n.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:s=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...E(s),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,s]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(s))}return r}t.childEnv=k},69317:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=s(i(17718)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),E=i(79141),D=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function A(e,i,s,r=0){const a=new Date,o=[];return(0,S.niceable)(i,s)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,s){const n=(0,x.spawnOptions)(s);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),A(r.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const s=i.quiet??!1,r=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||r?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!s&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,s){const n=(0,x.spawnOptions)(s);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),A(r.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const s=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(s.result),meta:{cmd:e,args:t,opts:i,result:s}})}},95237:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=o(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),b=i(7162),S=i(91464),P=i(36079),M=i(91641),_=i(49379),T=i(98462),E=i(90524),D=i(94845),k=i(51053),x=i(69317),C=i(24905),F=i(52289),I=i(95298),A=(0,c.lazy)((()=>(0,b.mkLogger)("child.ChildService")));async function O(e){const t=(0,S.ensureSuffix)(e,".js"),i=T.BaseFile.projectRoot(),s=T.BaseFile.for(u.default.cwd()),r=(0,D.isPacked)()?[i.join("bin",t),k.isElectron?i.join("app.asar",t):void 0]:[s.join("dist","library",t),s.join("dist","core",t),s.join("lib","library",t)];r.push(s.join("dist","app",t));for(const e of r)if(null!=e&&!0===await e.isNonEmptyFile((0,D.isPacked)()?p.KB:128))return A().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:D.isPacked,paths:r.map(v.toS)}});return A().throw("Failed to find path to "+e,{paths:r,fatal:!0})}t.pathToService=O,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class L{static async mk_(e,t={}){const i=t.pathToService??await O(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new L(e,i,t)}constructor(e,t,i){s.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,F.serviceExitTimeoutMs)(e),this.logger=(0,b.mkLogger)(this.name);const o=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&o.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,x.spawn)(u.default.execPath,o,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,s,"m",n).bind(this),onStderr:a(this,s,"m",r).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(E.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,S.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=L,s=new WeakSet,r=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const s=i(55568),r=i(43414),n=i(14889);t.serviceExitTimeoutMs=function(e){return(0,s.isSyncService)(e)?r.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),E=i(45512),D=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){s.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,r,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,s,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,s,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,s,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,s,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,s,"m",n).call(this),this._stopped=!1,u(this,s,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,s,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,s=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,s,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,s,"m",n).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,s,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,s,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const s=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(s))return a.join("$library",i.posixPathFrom(s));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(7304),r=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(s.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const s=i(51081),r=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,s.joinLines)(...(0,r.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const s=i(97742),r=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(s.env.maxLineLen)??s.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const s=i(43414),r=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(s.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>s.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const r=s(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(r.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const s=i(43414),r=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,r.isTrue)(e.timing)&&(s.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const s=i(4866),r=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const s=(0,a.toGt0)((0,l.env)()[t]);return null==s||i.includes(s)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${s}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,s.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const s=i(43414),r=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,r.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(s.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,r.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const s=i(4866),r=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,s.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const s=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:s,closeLabhashes:[s],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,s.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const s=(0,c.unlabhash)(e),n=b(s);return null!=s&&null!=n&&((0,r.pushUniq)(n.closeLabhashes,e),(0,r.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(s))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const s=i(4866),r=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],s=[];for(let r=0;re>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-s)])}function _(e){const[t,i,s]=v(e),r=(t+16)/116,n=i/500+r,a=r-s/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,s.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,s]=(0,f.clampRGB)(e),r=Math.max(t,i,s),n=r-Math.min(t,i,s),a=n?r===t?(i-s)/n:r===i?2+(s-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),r?n/r*100:0,r/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,s]=e,r=(200-i)*s/100;return[t,r>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,r/2]}function I(e){const[t,i,s]=e,r=i*(s<50?s:100-s)/100;return[t,r>0?2*r/(s+r)*100:0,s+r]}function A(e){const t=e[0]/360*6,i=e[1]/100,s=e[2]/100,r=Math.floor(t),n=s*(1-i),a=s*(1-(t-r)*i),o=s*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[s,a,n,n,o,s][l],255*[o,s,s,a,n,n][l],255*[n,n,o,s,s,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,s.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,s.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return A(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=A,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const s=i(75556),r=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,s,n]=e,[a,o,l]=t,u=i-a,c=s-o,d=n-l,h=(0,r.sqrt)(s**2+n**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,s.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,s,l]=e,u=(0,r.sqrt)(s**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=s*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+b:(D=(w+b)/2,D-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*k/(0,r.sqrt)(20+k),F=1+.045*E,I=1+.015*E*x,A=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,r.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*A)*O;return(0,r.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const s=i(11944),r=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,s.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,s.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const s=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=s&&(0,r.gt0)(i)?new c(s,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const s=i(4866),r=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,r.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),s=(0,r.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const s=(0,u.ciede2000_delta_e)(e.lab,i.lab),r=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(s);return(0,n.clamp)(0,100,r)*o}(e,t)));return s/i}t.dominantColorCorrelation=function(e,t){return e=(0,r.compact)(e),t=(0,r.compact)(t),(0,r.isEmpty)(e)||(0,r.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,s.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,s.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),s=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,s=4*t;g=Math.round(Math.max(i,Math.min(s,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,s).map((e=>{const s=(0,p.kmeans)(f,g,{...T,seed:e}),r=x(s.centroids,f.length);if(r.lengtht&&k(g-1);const n=r.slice(0,t),o=function(e){const t=new m.Average;for(const[i,s]of a.entries()){const r=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=n&&(0,l.times)(s,(()=>t.push(n.value)))}return t.p84}(n);return{...s,centroids:n,description:{kIn:g,kOut:s.centroids.length,kMerged:r.length,score:o,iterations:s.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:s}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),A=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(A),pixelCount:f.length}),{dominantColors:A,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const s of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,s)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,s))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,s.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:s=3}){if(s<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:s,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*r,retries:s-1}))}function D(e,t){const i=e.countSum,s=e.size;k(e);const n=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:s,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[s,r]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(s),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:s}):(e.delete(s),e.incr(a.labhash,r))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const s=[];for(const t of e){const e=s.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?s.push(t):e.size+=t.size}const r=t/100;return(0,n.sortBy)(s.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const s=i(4866),r=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,s.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,s=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),s.push(e[2])}const r=(i.stdDev??0)+(s.stdDev??0),n=r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const s=i(75556),r=i(61570),n=i(84253);t.isModeData=function(e){return(0,s.gt0)(e.mode0)&&(0,s.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const s=i(75556),r=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,s.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,s.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const s=i(42748),r=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),s=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,s)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const s=i(889),r=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),s=i?.groups;return null==s?void 0:f.for((0,c.parseExifDateTime)(s.start,t),(0,c.parseExifDateTime)(s.end,t),(0,a.toInt)(s.index),(0,a.toInt)(s.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>s.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>s.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,s=1){if(null==e||!e.isValid||null==t||!t.isValid)return;s=(0,a.clamp)(1,1e3,(0,a.toInt)(s,{defaultValue:1})),i=(0,a.clamp)(0,s-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),n=(t.toMillis()-r)/(s+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,s)}constructor(e,t,i,s=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=s,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((s=>function({start:e,end:t,middle:i,field:s}){return null!=e[s]&&null!=t[s]?i[s]:void 0}({start:e,middle:t,end:i,field:s})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof s.ExifDate||e instanceof s.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof s.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof s.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof s.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),s=E(e);if(null!=i&&null!=s)return(0,c.gt0)(t)&&t>s-i?{start:Math.round((i+s)/2-t/2),end:Math.round((i+s)/2+t/2)}:{start:i,end:s}}function C(e,t,i,s){const[r,n]=(0,a.sortBy)([x(e,i),x(t,s)],(e=>e?.start));return null!=r&&null!=n&&null!=r&&null!=n&&(r.start===n.start||r.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof s.ExifDate?r.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:s}){if(null==e||null==t)return!1;if(i??(i=k(e)),s??(s=k(t)),C(e,t,i,s))return!0;const r=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==r&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,s)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const s=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,s.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const s=i(39938),r=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,s.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,s.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const s=i(42748),r=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=s.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const s=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&s.push(i+e.s)}return s.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const s=t.exec(e);if(null==s||(0,u.isEmptyObj)(s.groups))return;const{year:r,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(s.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(s.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(s);return S({year:r,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(s.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof s.ExifDate&&t instanceof s.ExifTime))return;const i=new s.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:s.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:s.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:s.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof s.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=s.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const s=i(42748),r=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=s.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=s.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=s.DateTime.DATETIME_MED){return(0,c.opt)(s.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const s=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,s.pad2)(e.getMonth()+1),(0,s.pad2)(e.getDate()),"-",(0,s.pad2)(e.getHours()),(0,s.pad2)(e.getMinutes()),(0,s.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,s.pad2)(e.getUTCMonth()+1),(0,s.pad2)(e.getUTCDate()),"-",(0,s.pad2)(e.getUTCHours()),(0,s.pad2)(e.getUTCMinutes()),(0,s.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(889),r=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function k(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(s=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:s,month:r,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",s=15*(0,c.round)(e/15),r=Math.abs(s),n=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${E(n)}:${E(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function A(e,t){const[i,s]=[e,t].map(g.datedToMillis);return null==i||null==s?void 0:i-s}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(A(e,t),l.dayMs)},t.diffMillis=A,t.closeTo=function(e,t,i){return(0,u.mapOr)(A(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,s=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(s+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const s={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,s):k(e)?.setZone(r,s)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const s=(0,T.getZoneName)(e);return null!=s&&"UTC"!==s||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),E=i(50140),D=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=A({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const s=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=s)return s;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function A({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:s=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const s=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${s})`,f:i=>I(i,s,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:s}))if(r(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=A;class O{constructor(e={}){s.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,s,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,s,"m",n).call(this))),a(this,s,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=A({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,s=new WeakSet,r=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,s,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,s,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,s,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,s,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,s,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,s,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,s,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,s,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,s,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,s,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const s=i(66776),r=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,s.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,s.map)(o(e),(t=>{const i=l(e)??0;let s=(t+i/1e3).toString();for(t<10&&(s="0"+s),0===i&&(s+=".");s.length<6;)s+="0";return s}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const s=i(889),r=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof s.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const s=i(42748);t.isDateTime=function(e){return s.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const s=i(42748),r=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const s=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*s(),n=s(),a=s(),l=(0,o.toGt0)(s()),u=(0,o.toGt0)(s()),c=(0,o.toGt0)(s());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(s.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const s=i(4866),r=i(59694),n=i(75556),a=i(36218),o=(0,s.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const s=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(r=>{const n=s.format(new Date(2017,r));e.set(n,r+1),"short"===i&&"en-US"===t&&e.set(n+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const s=i(42748),r=i(4866),n=i(92507),a=i(43414);t.setupLuxon=(0,r.lazy)((async()=>{s.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>s.Settings.twoDigitCutoffYear=e)),s.Settings.defaultLocale=await(0,n.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const s=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=s&&Math.abs(s-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(s)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,s=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+s);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,A=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function O(e){return F(A().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=k(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof s.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof s.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function A(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function O(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||A(t,e))&&(!(0,u.gt0)(i)||O(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=A,t.validDay=O,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const s=i(889),r=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof s.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==s.UnsetZoneName&&e.zone.offset(Date.now())!==s.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===s.UnsetZoneName?void 0:e.zone?.name:e instanceof s.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const s=i(84253);t.AutoVacuumModes=(0,s.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const s=i(44726),r=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,r.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,s.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const s=i(4866),r=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,s.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,r.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const s=i(84253);t.CheckpointTypes=(0,s.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const s=i(4866),r=i(7162),n=i(61253),a=(0,s.lazy)((()=>(0,r.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const s of(0,n.sqliteFiles)(e)){const e=t.join(s.base).wip();i.push(e),await s.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const s=i(7162),r=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,s.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const s=Date.now();let a=0;const d=s+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const s=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+s+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(s)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const s=i(76387),r=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,s.isDated)(t)?[e,(0,r.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const s=i(4866),r=i(19658),n=i(43414);t.maxBatchPluckSize=(0,s.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(r.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const s=i(49411),r=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,r.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let r;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,s.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();r=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const s=Math.round(1.5*t);s>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+s+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=s)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:r});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const s=i(84253);t.RepairModes=(0,s.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const s=i(11944),r=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,r.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,s.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,s.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,s.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const s=i(95725),r=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...r.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...r.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,s.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const s=i(11944),r=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,r.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,s.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let r;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const s=i(4866),r=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,s.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),s=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:s.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,r.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:s.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,r.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(s).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const s=i(84253),r=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,s.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const s=i(84253);t.SynchronousModes=(0,s.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function x(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const s=i(4866),r=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,s.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const s=i(63410),r=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,s.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=s(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const s=i(39938),r=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,s.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const s=i(44470),r=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,s.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const s=i(70612),r=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,s.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const s=i(3955),r=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,s.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,r.cacheDir])if((0,s.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const s=i(39938),r=i(82798),n=i(3955),a=i(43414);function o(e){return(0,s.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const s=i(11944),r=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,s.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=s(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,s.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const s=i(38625),r=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,n.isPacked)()&&(0,s.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const s=i(38625),r=i(29405);t.doNotTrack=function(){return(0,s.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=s(i(87561)),n=i(49411),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const s of e)try{const e=(0,h.debom)(r.default.readFileSync(s)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,s]of(0,d.entries)(n))t.test(e)||(i[e]=s)}catch(e){console.warn("env(): failed to read .env file, "+s,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const s=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,s.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const s=i(84253);t.EnvKeys=(0,s.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const s=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,s.blank)(e))return i;let n;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:r}=n.groups;if((0,s.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=s(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const s=i(5712),r=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),s=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),s-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new s.Rate,t.fatalErrorRate=new s.Rate,t.internalErrorRate=new s.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,s=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,s).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const s=i(11944),r=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,s.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const s=i(11944),r=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,s.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const s=i(4866),r=i(88491),n=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),b=i(6231),S=i(43414),P=(0,s.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*r.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=r.dayMs){const i=e.getTime(),s=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(s,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),s=await this.eventCount(),r=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:s>=r,meta:{event:M(e),recentEventCount:s,maxErrorsPerDay:r,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,s.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const s=i(11944),r=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,s.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const s=i(53525);class r extends Error{constructor(e){super(e+s.InternalErrorFlag)}}t.InternalError=r},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const s=i(39938),r=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,s.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const s=i(11944),r=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const s=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(s??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,s.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const s=t?.path;return(0,r.blank)(s)||(i=(0,h.dedupeNeedle)(i,s,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const s=i(4866),r=i(87489);function n(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,s.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],s.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,s,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,r,"f").get(e),clearTimeout),n(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,s,"f").get(e);return null!=a&&(a.resolve(t),n(this,s,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,r,"f").get(e),clearTimeout),n(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},s=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const s=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,s.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const s=i(71239),r=i(4866),n=i(80313);function a(e){const t=new s.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const s=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,s.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const s=i(39938),r=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,s.notBlank)(e.result)||(0,s.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),E=i(43383),D=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),A=i(75556),O=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Q=i(21142),Y=i(80294),Z=i(10408),X=i(53525),ee=i(30114),te=i(25015),ie=i(19653),se=i(95694),re=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,se.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),s=(0,me.isStoredEvent)(e)&&(0,Y.isRecentMs)(i,t.EventTimeoutMs);return s&&"exit"===e.name?(0,A.gt)(i,V.StartTs):s}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,A.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,s,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),s.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,s,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),s=(0,C.parseJSON)(e);null!=s&&i.push(s)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const n=be((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,s,"m",f).call(this,e));r&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,A.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,s,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,s,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,O.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,s,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Z.errorToS)(e)+X.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=Se,r=Se,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Q.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),b.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,s,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Z.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+X.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+X.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const s=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){s.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const s=i(43947),r=i(79015);let n=!1;(0,s.later)((()=>(0,r.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},44982:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=s(i(87561)),n=s(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:s=!1,processUid:r,processGid:n}){if(null==e)return!1;const a=r??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(s&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const s=await(0,u.statMaybe)(i);if(null!=s){if(!s.isDirectory())return!1;if(t){if(!p(s,e))return!1}else if(t=!0,!m(s,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=s(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),s=await m(i.dir);for(const e of await(0,d.readdir_)(s))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(s,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const s=i(87561),r=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,s.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),E=i(88491),D=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),A=i(98510),O=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Q=i(91464),Y=i(2073),Z=i(69301),X=i(24586),ee=i(44982),te=i(77390),ie=i(51081),se=i(57400),re=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(s.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,s=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const s=be().get(i);if(null!=s)return s;const r=(0,he.resolve)(i),n=new Se(r,t);return be().set(i,n),be().set(r,n),n}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Q.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const s of t)!0===await e(s)&&i.push(s);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,s,"m",n).call(this)??await d(e=this.clearThisAndParent(),s,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const s of i)t.push(...(0,R.toA)(await s.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const s of i)if(s.isDirectory()){const i=await this._directoryEntryChild(s).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Z.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,X.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,s,"m",o).call(this,(0,Q.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,s,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,s,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const s=await e.sha();if(null!=s)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===s)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(s=>{const r=e.exec(s);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const s of e)for(const e of i)if((0,F.closeTo)(s,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const s=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(s,r)=>{try{const n=await e.f(s,(0,C.denull)(r));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{s.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const s=setInterval((async()=>{try{const s=await e.f();t(s)&&i.resolve(s)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||s.unref(),i.finally((()=>{clearInterval(s)}))}return i}}t.BaseFile=Se,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Q.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*E.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const s=i(43414),r=i(17310),n=i(63526),a=i(3955);function o(e){return t=>s.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const s=i(11944),r=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,s.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const s=i(49411),r=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,s.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=s(i(49411)),n=s(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const s=i(1487),r=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,s.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,s){super("fs.DirWatcher("+e+")",(()=>this.close()),s),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:s}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(s,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},48640:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b,S,P,M,_,T,E=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},D=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryIterator=t.Undone=t.Done=void 0;const k=i(49411),x=i(4866),C=i(11944),F=i(51367),I=i(75556),A=i(61570),O=i(8199),L=i(20636),R=i(17078),N=i(39784),B=i(13779),j=i(7162),z=i(91464),V=i(10408),W=i(25015),U=i(43414),q=i(78362),H=i(32421),G=i(35280),$=i(67220),J=i(64067),K=i(3955),Q=i(23872),Y=i(24948);t.Done={done:!0},t.Undone={done:!1};class Z{constructor(e,i,r){s.add(this),this.dir=e,this.ctx=i,this.parent=r,this.start=Date.now(),n.set(this,void 0),a.set(this,[]),o.set(this,[]),l.set(this,[]),u.set(this,[]),c.set(this,void 0),d.set(this,!1),h.set(this,0),f.set(this,0),m.set(this,0),p.set(this,0),g.set(this,0),this.rootDir=(0,x.lazy)((()=>this.parent?.rootDir()??this.dir)),this.pathFromRoot=(0,x.lazy)((()=>(0,K.posixPathFrom)({nativePath:this.rootDir().dir},this.dir))),this.nextTimeout=(0,x.lazy)((()=>U.Settings.statTimeoutMs.valueOrDefault+(0,I.clamp)(0,512,10*(512-this.depth())))),v.set(this,(0,x.lazy)((async()=>{const e=await(0,J.whyExcludedDirectory)(this.dir)??(!this.isRoot&&await(0,H.isPosixMountpoint)(this.dir)?"nested mountpoint":void 0);if(null!=e)return D(this,n,"f").info("skipping ignorable dir, "+this.dir,{details:e}),this.cancel({state:Y.SyncDirStates.skipped,details:e}),t.Done}))),S.set(this,(0,x.lazy)((async()=>{const[e,t]=(0,B.partition)((0,N.toA)(await this.dir.children()),(e=>D(this,s,"m",b).call(this,e)));for(const t of e)(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.skipped,details:"this was scanned in a prior incomplete sync"});D(this,u,"f").push(...t.filter((e=>e.isDirectory()))),E(this,p,D(this,u,"f").length,"f");const i=t.filter((e=>e.isFile())),[r,n]=(0,B.partition)(i,W.isSidecarExt);D(this,a,"f").push(...n),D(this,l,"f").push(...r),E(this,f,D(this,a,"f").length,"f")}))),(0,Y.syncReport)().onProgress({path:e.nativePath+k.sep,from:"DirectoryIterator",state:Y.SyncDirStates.scanning}),this.name="dir.DirectoryIterator("+e+")",E(this,n,(0,j.mkLogger)(this.name),"f")}get isRoot(){return null==this.parent}isDone(){return D(this,d,"f")}status(){return{root:this.rootDir().nativePath,path:this.pathFromRoot(),isDone:this.isDone()}}cancel(e){return D(this,d,"f")||(E(this,d,!0,"f"),(0,Y.syncReport)().onProgress({path:this.dir.nativePath+k.sep,from:"DirectoryIterator",state:Y.SyncDirStates.canceled,...e,elapsedMs:Date.now()-this.start})),t.Done}depth(){return(0,z.countChars)(this.dir.nativePath,k.sep)}async next(e){var i;try{D(this,n,"f").trace("next() starting",{runMs:e-Date.now()});const r=await(0,L.thenOrTimeout)(D(this,s,"m",y).call(this,e),this.nextTimeout());return D(this,n,"f").trace("next() finished",{result:r}),r===L.Timeout?(E(this,g,(i=D(this,g,"f"),++i),"f"),D(this,n,"f").warn(".next() timed out",{statTimeoutMs:U.Settings.statTimeoutMs.valueOrDefault,timeoutCount:D(this,g,"f")}),D(this,g,"f")>3?(D(this,n,"f").warn(".next(): too many timeouts, giving up on this directory."),this.cancel({state:Y.SyncDirStates.timeout,details:"Failed to scan, even after 3 retries"})):t.Undone):(E(this,g,0,"f"),r)}catch(e){return D(this,n,"f").warn("next() failed",{error:e}),this.cancel({state:Y.SyncDirStates.failed,details:"Error thrown during scan: "+(0,V.errorToS)(e)})}}}t.DirectoryIterator=Z,r=Z,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,g=new WeakMap,v=new WeakMap,S=new WeakMap,s=new WeakSet,y=async function(e){return(D(this,d,"f")?t.Done:void 0)??await D(this,v,"f").call(this)??await D(this,S,"f").call(this)??await D(this,s,"m",P).call(this,e)??await D(this,s,"m",M).call(this,e)??await D(this,s,"m",_).call(this,e)??await D(this,s,"m",T).call(this)},w=function(e){return this.ctx.ended?this.cancel({details:"DirectoryWalker was ended"}):D(this,d,"f")?t.Done:(0,$.isPaused)()||Date.now()>e?t.Undone:void 0},b=function(e){return D(this,n,"f").tap({msg:"shouldSkipChild()",result:(0,C.isNotEmpty)(this.ctx.startAtNativePath)&&(0,O.cmpArr)((0,K.splitNativePath)(e.nativePath),this.ctx.startAtNativePath,!1)<=0,meta:{child:e.base}})},P=async function(e){var t;const i=[];let r;for(;null==r&&(0,C.isNotEmpty)(D(this,a,"f"));){const o=D(this,a,"f").shift();E(this,h,(t=D(this,h,"f"),++t),"f");const l=await(0,Q.whyRejectFileSimple)(o);null!=l?(D(this,n,"f").debug("maybePopChildFile()",{child:o,whyReject:l}),(0,Y.syncReport)().onProgress({path:o.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.rejected,details:l})):i.push(o),r??(r=D(this,s,"m",w).call(this,e)),null!=r&&D(this,n,"f").trace("maybePopChildFile() timeout",{timeout:r})}return(0,C.isNotEmpty)(i)&&(D(this,n,"f").trace("maybePopChildFile()",{toAdd:i}),await this.ctx.fileHandler(i),D(this,o,"f").push(...i)),r},M=async function(e){for(;(0,C.isNotEmpty)(D(this,l,"f"));){const t=D(this,l,"f").shift();if(U.Settings.tagAlbumFilenames.values.includes(t.base))(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.note,details:"sidecar will be checked for for album metadata"});else{const e=D(this,o,"f").filter((e=>(0,q.isSidecarOf)(e,t)));(0,C.isNotEmpty)(e)?(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.note,details:"sidecar will be processed with "+(0,F.andList)(e.map((e=>e.base.normalize())))}):(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.rejected,details:"sidecar will be ignored (no importable file was found to be relevant to this sidecar's name)"})}const i=D(this,s,"m",w).call(this,e);if(null!=i)return D(this,n,"f").trace("handleSidecars() timeout",{timeout:i}),i}},_=async function(e){var t;let i;for(;null==i&&(null!=D(this,c,"f")||(0,C.isNotEmpty)(D(this,u,"f")));){if(null==D(this,c,"f")){const e=D(this,u,"f").shift();null==e||(D(this,n,"f").trace("delegating to child dir, "+e),E(this,m,(t=D(this,m,"f"),++t),"f"),E(this,c,new r(e,this.ctx,this),"f"))}if(null!=D(this,c,"f")){const t=await D(this,c,"f").next(e);(t?.done??!0===D(this,c,"f")?.isDone())&&E(this,c,void 0,"f")}i=D(this,s,"m",w).call(this,e)}return i},T=async function(){if((0,C.isNotEmpty)(D(this,a,"f"))||(0,C.isNotEmpty)(D(this,u,"f"))||null!=D(this,c,"f"))return D(this,n,"f").error("maybeCompleteResult: not done (?!)",(0,A.pick)(this,"result","pendingChildren","childDelegate","pendingChildDirs")),t.Undone;if(!D(this,d,"f")){E(this,d,!0,"f");const e=await(0,G.mkFolderUrl)(this.dir.nativePath),t=e?.with({query:null}),i=t?.toString();(0,Y.syncReport)().onProgress({path:this.dir.nativePath+k.sep,state:Y.SyncDirStates.scanned,from:"DirectoryIterator",details:`${D(this,h,"f")}/${(0,R.plur)(D(this,f,"f"),"file")} and ${D(this,m,"f")}/${(0,R.plur)(D(this,p,"f"),"directory","directories")}`,url:i,elapsedMs:Date.now()-this.start}),await this.ctx.directoryListener(this.dir)}return t.Done}},97463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryWalker=void 0;const s=i(4866),r=i(88491),n=i(75556),a=i(19658),o=i(28807),l=i(91641),u=i(17354),c=i(43414),d=i(76052),h=i(48640),f=i(3955);class m extends o.EndableInterval{constructor(e,t,i,s,r){super({name:"dir.DirectoryWalker("+e.nativePath+")",callback:()=>this.runChunk(),intervalMs:m.IntervalMs(),rank:l.EndableRanks.first}),this.root=e,this.fileHandler=t,this.directoryListener=i,this.highPriority=!0,this.runChunk=(0,u.oneAtATime)({runLaterIfBusy:!1,fn:async()=>{if(!a.isTest&&(0,d.doNotRun)(this))return;const e=await this.iterator.next(Date.now()+this.runMs);this.logger.debug("runSlice()",{result:e}),!0===e?.done&&(this.logger.info("runSlice(): completed iteration"),this.end())}}),this.runMs=r??(0,n.clamp)(1,100,c.Settings.cpuBusyPercent.valueOrDefault)/100*m.IntervalMs(),null!=s&&((0,f.containedByNativePath)({ancestor:this.root.nativePath,descendant:s})?this.startAtNativePath=(0,f.splitNativePath)(s):this.logger.error("bad startAtNativePath: ignoring.",{root:this.root.nativePath,startAtNativePath:s})),this.iterator=new h.DirectoryIterator(e,this),this.runChunk()}}t.DirectoryWalker=m,m.IntervalMs=(0,s.lazy)((()=>2*r.secondMs))},93033:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=s(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},s=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(s.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(s.dir,`${s.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${s.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},s=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(s.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(s.dir,`${s.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${s.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),E=i(20902),D=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),A=i(98462),O=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const s=(0,B.isSimpleFile)(e)?e:A.BaseFile.for(e),r=V.test(t)||s.isDirectorySync(),n=(0,R.native2posix)(s.nativePath),a=r?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(s.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(s.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,s,"m",r).bind(this)):{}}}s=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,s){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new U(`**/${t}/${r[0]}/`,s)),r.length>1&&e.push(new U(`**/${t}/(${r.join("|")})/`,s))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const s=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",s,"Linux /var"),t("mnt",s,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Q=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:se,notInHiddenPhotoStructureDir:ae,notNoMedia:re,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Q();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const s=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,n]=(0,g.partition)(s,(e=>e.pattern.endsWith("/")));return{dir:r,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function X(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...X(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function se(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=X,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),s.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,s,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,s=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),b=i(77696),S=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){s.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,r.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,s,"m",a).call(this)}),o(this,r,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,r=new WeakMap,s=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,r,"f").info("cleanup(): starting",{root:t,staleMs:(0,b.fmtFullDuration)(this.staleMs," ")});const i=await l(this,s,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,r,"f").warn("cleanup(): ENOENT "+e,t),(0,S.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,r,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,r,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,r,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,r,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const s=i(87561),r=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof s.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const s=i(93977),r=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,s.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const s=i(53221),r=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,s.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,n.blank)(r)||(0,n.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const s=i(66776),r=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,s.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:s,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:s})));try{for(const t of u)if(!0!==await(0,r.thenOrTimeout)(t.acquire_(),s))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),_=i(92332),T=i(11944),E=i(37609),D=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),A=i(20636),O=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,r,Math.max(Date.now(),w(this,r,"f",n)+1),"f",n),(0,T.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",n)),N.serviceName.prior(),(0,O.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,O.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),s.add(this),this.opts=e,l.set(this,b(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,s,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,s,"m",f).call(this,e)??w(this,s,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);b(this,c,setInterval((()=>w(this,s,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,s,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,s,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,A.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,s=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,s,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,s,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,s,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,s,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const s=i(39938),r=i(44726),n=i(82798),a=i(95725);function o(e){return(0,s.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,s.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,s.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),E=i(79015),D=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),A=i(95725),O=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const s=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,s),s.on("close",(()=>{this.path2watcher.delete(e)})),s.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,A.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),s.add(this),this.args=e,this.id=(0,F.uid)(),r.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,s,"m",o).call(this),!0===e?.isFile()&&await c(this,s,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,O.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,s,"m",o).call(this):!a&&!!i.isFile()&&await c(this,s,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,r,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,A.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const s=i(39938),r=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,s.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let s=e;for(const e of i.aggressive?d:c){const t=s.match(e);if((0,n.gt0)(t?.index)){const e=s.slice(0,t.index).trim();e.length>0&&(s=e)}}return e===s?e:f(s,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,s.blank)(i))return e;const r=(0,u.parsePosixPath)(i),n=h(r,{aggressive:!1});return[...t,n+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),s=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(s),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const r=s(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const s=(0,o.toS)(e).match(this.pattern);null!=s&&this.push(s[1]??s[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([r.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=s(i(44470)),n=s(i(87561)),a=i(76402),o=s(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=s(i(6005)),n=s(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const s=(0,y.toNativePath_)(e);if(i){const t=b().get(s);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:s,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:s,prior:t}),b().delete(s)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const s=r.default.createHash(i);return await(0,a.pipeline)([e,...t,s]),s.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const s=i(4866),r=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,s.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const s=i(39938),r=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,s.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const s=i(4866),r=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,s.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,r.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const s=i(84492),r=i(44726),n=i(82798);class a extends s.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const s=(this._prior+(0,n.toS)(e)).split((0,r.newlineRe)()),a=s.pop();this._prior=a??"";let o=!1;for(const e of s)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=s(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const s=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),s=(0,r.toNativePath_)(t);return null!=i&&null!=s&&i===s}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,s.actualPath_)((0,r.toNativePath_)(e))===await(0,s.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const s=await Promise.race([T(e,t),D(e,t)]);return t.halt(),s}(t.nativePath)))}async function T(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const s of t){if(!0===i?.halted)return null;if(P(s.basename))return y().tap({msg:e+" has a noMedia child, "+s.basename,result:!0});if(s.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,s.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=s(i(44470)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",s=n.default.parse(t?.path??e);return{...s,ext:(s.ext??"")+i,base:(s.base??"")+i}}function E(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const s=e.acceptSelf??!1;return t===i?s:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const s=e(t),r=e(i);return null!=s&&null!=r&&(g.isLinux?s===r:(0,m.equalsIgnoreCase)(s,r))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=E,t.grandParentBasename=function(e){return E(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),s=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(s))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===s?"":(0,m.stripPrefix)((0,y.native2posix)(s).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const s=x(e),r=[],n=[s.pop()];for(;s.length>0;)if(r.length=t){s.unshift(r.pop());break}}else if(n.unshift(s.pop()),F([...r,...n]).length>=t){s.push(n.shift());break}return s.length>0&&r.push("โ€ฆ"),F([...r,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=s(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const s=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of s){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:s})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var s,r,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),E=i(61570),D=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),A=i(14889),O=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Q=i(19209),Y=i(25116),Z=i(32421),X=i(53719),ee=i(46573),te=i(98462),ie=i(21084),se=i(25015),re=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),s.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Q.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:A.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),s=new pe(i,t);return(0,O.isString)(e)&&me().set(e,s),me().set(i,s),s}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Q.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,s=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(s)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,se.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,se.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,se.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:s=!1,timeoutMs:r,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async s=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(s),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&s?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,O.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,O.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:s=!1,timeoutMs:r,dirty:n=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:s,timeoutMs:r,dirty:n},(async()=>{const s=this.wip();try{await s.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(s),r);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>s.clear().isNonEmptyFile(i)),{timeoutMs:A.ShortCommandTimeoutMs,intervalMs:250}))return await s.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(A.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await s.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,s,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,s,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,X.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(A.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*X.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,s=new WeakSet,r=async function(e){let t,i=e;const s=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await s.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,s.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>s.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(r.size,await s.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await s.size({refresh:!0})});await this.maybeVerifySameOrThrow_(s),i=e.eql(s)?e:await s.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${s?.nativePath}) failed: ${t}`),await s.unlink(),s.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const s=await this.stat_(),r=s?.size;return null==s||null==r?this.pflog().throw("Can't copy missing files"):(r>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const s=i(11944),r=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function A(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function O(e){return[...A(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,s.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=A,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...A(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...A(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...A(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=s(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,n.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",s=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(s[0],t)&&s.unshift(),i+s.join(r.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=s(i(49411)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const s=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(s,e))return s}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const s=i(44470),r=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,s.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const s=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const r=i??(await(0,s.stat)(e)).size-t,a=Buffer.alloc(r);return n=await(0,s.open)(e,"r"),await(0,s.read)(n,a,0,r,t)}finally{(0,r.mapGte0)(n,s.close)}}},41544:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const s=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,s.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const s=i(84492);class r extends s.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=s(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),s=E(e),r=await(0,h.thenOrTimeout)(s,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):E(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=s(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const s=i(94383),r=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new s.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const s=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,s.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=s(i(87561)),n=s(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),s=S(t);if(i!==s)return"inconsistent file type: "+i+" โ‰  "+s;for(const i of["size","mtime"]){const s=e[i],r=t[i],n=(0,u.diff)(P(s),P(r));if(null==n||n>1)return"unmatched "+i+": "+s+" โ‰  "+r}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=s(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const s=i(43414);t.statTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const s=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const s=new n(t,i,!0);return s.read(e),s.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,s.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,s.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=s(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,s)=>{!1===e.write(t,(e=>{e&&s(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),E=i(91641),D=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),A=i(18849),O=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,s,r,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=s,this.from=r,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,O.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),s.add(this),r.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,r,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,A.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const s=Date.now(),r={ts:s,at:new Date(s).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([r],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:s}){const r=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await s(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-r,...n,state:a}),n}catch(s){throw this.logger.warn("wrap_() caught error",{error:s,stack:s.stack}),this.onProgress({path:e,from:i,state:s instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(s),elapsedMs:Date.now()-r}),s}}get output(){return l(this,n,"f")??l(this,s,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,r,"f")}}t.SyncReport=$,r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=function(){return u(this,r,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,r,"f").nativePath),this.logger.info("Opening new report: "+l(this,r,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,r,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,r,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},59220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unprocessedPaths_=t.readSyncReport_=void 0;const s=i(87561),r=i(84492),n=i(76402),a=i(57153),o=i(39938),l=i(91464),u=i(51081),c=i(13348),d=i(95725),h=i(24948),f={header:!0,skipEmptyLines:"greedy"};t.readSyncReport_=async function(e){const t=(await(0,c.readLines_)(e)).join(u.Newline);return(0,a.parse)(t,f)};class m extends r.Transform{constructor(e=new Set,t=new Set,i,s){super({objectMode:!0}),this.enqueued=e,this.settled=t,this.accept=i,this.fileDoneStates=s}_write(e,t,i){if(null!=e&&h.SyncFileStates.includes(e.state)&&(0,o.notBlank)(e.path)&&this.accept(e.path)){const t=e;"enqueued"===t.state?this.enqueued.add(t.path):this.fileDoneStates.has(t.state)&&this.settled.add(t.path)}i()}}t.unprocessedPaths_=async function({syncReportJsons:e,acceptPath:t=(()=>!0),fileDoneStates:i=h.FileDoneStates}){const r=new Set,o=new Set;for(const l of e)await(0,n.pipeline)((0,s.createReadStream)((0,d.toNativePath_)(l)),(0,a.parse)(a.NODE_STREAM_INPUT,f),new m(r,o,t,i));const u=[...r].filter((e=>!o.has(e)));return(0,l.sortIgnoreCase)(u)}},22143:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=s(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=s(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const s=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(s,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(r.default.ensureFile(s),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const s=i(4866),r=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,s.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,s.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,s.lazy)(g),t.libraryUidStore=g,(0,r.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(s){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:s})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=s(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const s=i(39938),r=i(14889),n=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,s.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const s=i(84492),r=i(34996);class n extends s.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=s(i(44470)),n=s(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=s(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const s=[],n=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>s.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>s.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>s.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(s))throw new f.WrappedError("zPipe("+e+") failed",{causes:s,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},44606:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=s(i(52167)),n=i(43383),a=i(43947),o=i(77125),l=i(7162),u=i(55568),c=i(14889),d=i(20681),h=i(43414),f=i(19209),m=i(36297),p=i(79403),g=(0,n.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({later:async()=>{try{if(!(0,u.isWebService)()){const e=f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}).toString(),t=await r.default.get(e,{timeout:c.ShortCommandTimeoutMs}),{status:i,data:s}=t;if(m.HttpStatusIs.ok(i)&&(0,o.isHealthCheckSummary)(s))return s.libraryDir!==(h.Settings.libraryDir.valueOrDefault??null)?void g().error("getHealthSummary(): libraryDir mismatch",{local:h.Settings.libraryDir.valueOrDefault,remote:s.libraryDir}):(g().debug("getHealthSummary()",{url:e,status:i,data:s}),s);g().warn("getHealthSummary(): invalid response",{url:e,status:i,data:s})}}catch(e){g().warn("Failed to get health check summary from web service",{error:e})}},ttlMs:c.ShortCommandTimeoutMs}),t.getLocalHealthSummary=(0,d.lazyAsync)({later:()=>p.HealthCheck.awaitSettled(),ttlMs:c.ShortCommandTimeoutMs}),(0,a.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const s=i(53719),r=i(79403),n=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...r.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:r.HealthCheck.lastErrors(),timeoutMs:(0,s.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),E=i(66776),D=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),A=i(13779),O=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Q=i(62905),Y=i(18295),Z=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class X{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,r,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,r,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,r,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,r,"f",l).toA()}static addLoadingMsg(e){v(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Z().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,r,"f",h).entriesByCountDesc()}),(0,E.map)((0,A.leastBy)(e,(e=>[v(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,r,"f",h).incr(e.msg))),Z().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return v(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=r.summary();if(t.settledCountv(r,r,"f",a).enqueue({name:this.id,l:()=>v(this,s,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>r.onResultChange(),onError:()=>r.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,s,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,A.partition)(e,(e=>"button"===e.type||"POST"===e.method)),s={};return(0,S.isNotEmpty)(i)&&(s.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(s.buttons=(0,S.uniqBy)(t)),s}t.HealthCheck=X,r=X,s=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,r,"f",n),(e=>!e.isPending)),v(this,r,"f",n)},m=function(e){const t=Z().tap({level:"info",msg:"#summary()",result:(0,Y.summarizeHealthChecksSync)({errors:v(this,r,"f",l),skipPending:v(this,r,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,r,!0,"f",u),t.state!==v(this,r,"f",c).last?.state&&v(this,r,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Z().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,s,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,s,"m",g).call(this,i)}catch(e){return v(this,s,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=r.normalizeMsg(e.msg),s=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,S.compact)([...e?.links??("ok"===s||"pending"===s?this.okLinks:"warn"===s?this.warnLinks:"no-library"===s?this.noLibraryLinks:"error"===s?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:s,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Q.HealthCheckLevelToLogLevel[s],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,s,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new O.BoundedList(10)},u={value:!1},c={value:new O.BoundedList(10)},d={value:new O.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},X.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(r,r,"f",f),(e=>e.sortBy))))),X.summary=(0,b.lazy)((()=>v(r,r,"m",m).call(r))),X.resetDebounced=(0,N.debounce)((()=>r.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const s=i(84253);t.HealthCheckIds=(0,s.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const s=i(36535),r=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,s.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const s=i(11944),r=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,s.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=s(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:s}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(s,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const s=i(11944),r=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:s}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),s))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,s.uniq)((0,s.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,s.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,s.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const s=i(47261),r=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),E=i(43414),D=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),A=i(14489),O=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,r.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[s.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const s=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==s){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(s);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:s,whyRejected:e})}const r=i.sha??await s.sha();if(null!=r)if(!0!==await(0,t.isBadSha)(r))try{return await this._build(s,i)}catch(t){e.push(t),L().set(r,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",s);else this.logger.info("skipping: cannot read SHA",s),e.push(new Error("Cannot read "+s.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,O.throwIfInvalidFile_)(e);const i=await e.size(),s=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:s,best:t.uri}),null==i||null==s)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:a,height:o,sha:l,mimetype:u}=t;if(null==r||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:s,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const s=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(s,r)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(s,r);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),s=await this.priorIfValid_(t,i);if(null!=s)return s;const r=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,s]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(s.reducer.name,i.width).wip();e=s.resize(i,e),t=i,s.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&s.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await s.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+s.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),s=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),r.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(s)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const s=i(13783),r=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,s){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(s)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),s=(0,o.toInt)(i[0]),r=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(s)?{file:t,assetId:s,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:s,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,s.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){s.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,s,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",s=t?.[i];if(!(0,o.isEmpty)(s))return s;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},s=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const s=i(84253);t.CropStrategies=(0,s.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=s(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;ir?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const s=i(11944),r=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,s.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,s=Math.round(Math.sqrt(t*i));return{width:s,height:Math.round(s/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const s=u(e,i);return null==s?[]:a.Rotations.filter((e=>u(c(t,e),i)===s))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const s=i(4866),r=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,s.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const s=i(11944),r=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),s=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,s.push([a,n])))}return s},t.equivalentFitSizes=function(e,t){return(0,s.includesAll)((0,s.compactBlanks)(e).map(l),(0,s.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const s=i(39938),r=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,s.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,s.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,s.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,s.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,s.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const s=i(4866),r=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,s.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,s.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const s=i(39938),r=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,s.blank)(e)&&n.test((0,r.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const s=i(93977),r=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,s){const r=await(0,t.imageCacheDir_)();i??(i=e.name),s=(0,c.ensurePrefix)(s??e.ext,".");const n=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+s);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:s,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,s.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),s=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await s.parent().mkdirp_(),s},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:s}){return(await P(e,t,i)).applyIfEmpty_({fn_:s,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,s){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:s,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(s){return b().throw("withImgCache_() failed",{error:s,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=s(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),E=i(68107),D=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function A(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const s=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:s});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const s=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return s.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:A}),t._imageHash_=A,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),b=i(60346),S=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),E=i(72461),D=i(36143),k=(0,s.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,r.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,r.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),s=Math.max(e.length,t.length,i);return(s-i)/s};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const s=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),r=i*i;for(;s.length%r!=0;)s.unshift(0);return s.length===r||t?s.slice(0,r):s.slice(0,r).map(((e,t)=>4*e+2*s[t+r]+s[t+2*r]))}function I({a:e,b:t,greyscale:i,dim:s=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,s),l=F(t,i,s);(0,r.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function A(e,t,i="debug",s={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),s)})}function O(e,t,i={}){const s=(0,E.toImageHash)(e),r=(0,E.toImageHash)(t);if(null==s||null==r)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(s.isGreyscale??C(s.meanHash))||(r.isGreyscale??C(r.meanHash))),f=I({a:s.meanHash,b:r.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(s,r)}),m=I({a:s.diffHash,b:r.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:s.dctHash,b:r.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(s.dominantColors,r.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=s.mimetype===r.mimetype,v=(0,T.aspectRatio)(s),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(r,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),A=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(v)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=A,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:A,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(s,"uri","id","assetId"),b:(0,d.pickCompact)(r,"uri","id","assetId"),...V}),{a:s,b:r,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const s=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",r=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(r,e).map((e=>e.toString(2))).join("")+s))))},t.hammRatio=I,t.isSimilarImage=A,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",s={}){return A(e,t,i,{rotationsToCheck:[0],...s,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,s,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,s,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,s,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(s,s,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,s=m,r={value:[]},m.UHD8k=new s("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new s("uhd5k",5120,2880,h.Fit,!1),m.UHD=new s("uhd4k",4096,2160,h.Fit),m.QHD=new s("qhd",3120,1440,h.Fit),m.FHD=new s("fhd",1920,1080,h.Fit),m.HD=new s("hd",1280,720,h.Fit),m.WVGA=new s("wvga",720,480,h.Fit),m.QVGA=new s("qvga",320,240,h.Fit),m.QQVGA=new s("qqvga",160,120,h.Fit),m.S480=new s("s480",480,480,h.Square),m.S240=new s("s240",240,240,h.Square),m.S120=new s("s120",120,120,h.Square),m.S60=new s("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const s=i(4866),r=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),s=i?.capturedAt;null!=s&&(delete i.capturedAt,(0,n.assignFields)(i,s.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=s(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,s)=>t>=(0===s?e[i]:s%i==0?e[s-i]:e[s-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),s=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(s.map(c)),diffHash:(0,n.flatten)(s.map(d))}}},35254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const s=i(4866),r=i(18941),n=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,s.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const s=i(4866),r=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,s.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const s=i(11944),r=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const s=Math.abs(e-t);return s>i?void 0:s}))??e))}function c(e,i,s=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),s)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const s=Math.abs(t.i-e);return s[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const s=i(4866),r=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,s.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,s.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,s,n,a]=e.split("\t"),o=(0,r.toGt0)(n),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:s,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const s=i(4866),r=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,s.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,s){const r=(0,d.lteBoth)(e,s)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(s,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=s(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const s=i(84253);t.SharpFailOns=(0,s.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(889),n=s(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),E=i(84685),D=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),A=i(49312),O=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,s,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const s=B().addParameterContext(e.nativePath);j();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return s.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void s.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return s.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),O=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||O||L||z)s.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:O,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)s.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof r.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){s.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else s.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return s.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...r};s.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){s.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const s=i(43649),r=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=r.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*r.secondMs},p1:{x:20*o.MB,y:12*r.secondMs}},p={p0:{x:11*o.MB,y:12*r.secondMs},p1:{x:26*o.MB,y:24*r.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,r=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,s.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+r+n+c+d),dbMs:i,tagMs:r,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,s.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=s(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),s=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(s)&&_().throw(s,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const s=i(4866),r=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,s.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,s.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const s=i(4866),r=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),E=i(49586),D=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),A=i(68107),O=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,s.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const s=j("extractMaxBitrate",e),r=D.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,r))return s.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return s.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return s.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,s.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,s.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),s=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,R.cachedImageFile_)(s,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await s.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(s,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,L.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:s,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,O.commandTimeoutMs)()}),r.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const s=i.MIMEType;if(!(0,F.isVideoMimeType)(s))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:s}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,s);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:s,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const s=j("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,n.isTrue)(i?.force))return s.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void s.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return s.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return s.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),s=await(0,C.readRawTags)(e),r=(0,x.extractDurationSec)(s),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,n,1.5),meta:{srcDurationSec:r,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return s.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,r={src:e,...V(e,d)},n=J(o,r.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?s.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),s.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{s.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(r));0!==o.code&&s.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const s=i(11944),r=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),s=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+s),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,s.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,s.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...A(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const s=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(s))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const s=i(75556),r=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,s.toGt0)(n.Settings.ffmpegThreads.value)??(0,s.clamp)(1,6,(0,s.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const s=i(4866),r=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,s.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const s=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(s,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,s.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),s=await(0,b.dimensions)(e);if(null==s)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(s),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(s)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...E,...D,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),A=[];function O(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const s=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});A.push(s)}}I.on("error",O),I.stderr.on("data",O);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,r.isNotEmpty)(A))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:A,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const s=i(4866),r=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,s.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},87308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.r=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(43383),l=i(87748),u=i(66776),c=i(8199),d=i(7162),h=i(29731),f=i(42041),m=i(4586),p=i(98250),g=i(10309),y=i(43414),v=i(53719),w=i(10508),b=i(69060),S=i(13700),P=i(59714),M=(0,o.defer)((()=>(0,d.mkLogger)(_().l))),_=(0,s.rolazy)((()=>(0,w.j)("G8oAKIzTFfOihHWPgG6m/h0h65IqCWu72UHSOixdfW12GgbIbSdJW2sLEmvLsqcHfOPXk00SqojDRomicXUE+MuLfPaoTzFWZPq8AdmWyQVUWERkBLoYBhqafaAvY27+LDra0blcQ4Vnjn/ukQh/C4o0cd0B")));async function T(e){const t=await(0,S.sids)({timeoutMs:(0,v.commandTimeoutMs)()});if((0,r.isEmpty)(t))return M().warn("no-op: empty sids");const i=(0,l.stringify)({uids:[...t,e],coupon:y.Settings.coupon.valueOrDefault,version:f.version}),s={..._().r,body:i},n=await(0,g.request)(_().u,s);M().info(_().u,{req:s,response:n}),n.ok?await(0,P.writeLicense)(JSON.parse(n.body)?.[_().a],(0,v.commandTimeoutMs)()):M().warn(_().u,{req:s,response:n})}t.r=(0,s.rolazy)((async()=>{const e=_().s+": ";try{if(!y.Settings[_().s].valueOrDefault)return M().debug(e+"no-op (settings disabled)");const t=(await(0,b.m)()).filter((e=>null!=e.l&&(0,n.notBlank)(e.s))),i=new Date,s=t.find((e=>e.ok&&(0,c.gt)(i,e.l?.exp)));if(null!=s)return M().debug(e+"no-op: ",s);const r=await(0,u.map)((0,m.configDir)(),(e=>p.PosixFile.for(e).join(_().s+"-v"+f.versionMajor+"."+f.versionMinor).mkdirp_()));for(const s of t){if((0,n.blank)(s.s)||null==s.l||ie.startsWith("cu:")));if(null!=t){if(await(r?.join((0,h.shortFsStringSha)(s.s,14)+".txt").applyIfEmpty_({fn_:async i=>{await T(t),await i.writeJson_({l:s.l,at:Date.now()}),M().warn(e+"requested",s)},timeoutMs:(0,v.commandTimeoutMs)()})),await(0,b.p)())break}else M().debug(e+"skipping (no cu)",s)}}catch(t){M().warn(e+"failed",t)}}),15*a.minuteMs)},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const s=i(65628);t.j=function(e){return JSON.parse((0,s.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const s=i(39938),r=i(43414),n=i(69060);t.getEmail=async function(){const e=r.Settings.email.value;if((0,s.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,s.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const s=i(35666),r=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,s){this.s=e,this._l=t,this._sids=i,this.meta={src:s}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,r.uniq)(e.map(c.getScheme)),i=(0,r.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),s=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=s,this.meta[(0,u.k)().m]=i,a&&s}cmpVal(){return[this.ok,-(s.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const s=i(4866),r=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),E=i(43414),D=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,s.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function A(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),s=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==s)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const r=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==r)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(s),i[(0,t.k)().r]=new Date(r),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function O(e,i,s,r){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await A(e),sids:null!=r?r:await(0,C.sids)({timeoutMs:s}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],s=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of s.reverse()){const s=await O((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=s&&i.push(s)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=A,t.v=O,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const s=await O(e,t,i);return(0,a.isTrue)(s?.ok)&&s instanceof k.L?s:void 0},t.m=(0,s.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return O(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const s=i(91144),r=i(4866),n=i(39938),a=i(10508);t.l=(0,r.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,s.decode)(e).payload;if(null==i)throw new Error("Missing payload");const r=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===r));if(null==a)throw new Error("Unknown key");return s.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const s=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(s)||w.includes(s.toLowerCase())||null!=s.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(s,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){s.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of r(this,s,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return r(this,s,"f").size}addUids(e){for(const t of e)null==v(t)||r(this,s,"f").has(t)||(r(this,s,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},s=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const s=i(11944),r=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,s.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,s.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,r.notBlank)(e)&&null==e.match(F)))}async function A(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],s=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:s}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,s.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,A,O,L,B,U,q],s=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of s)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...s]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const s=i(88491);t.UserTimeoutMs=7*s.secondMs},59714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const s=i(43383),r=i(66776),n=i(7162),a=i(29731),o=i(46852),l=i(4586),u=i(82341),c=i(56958),d=i(98462),h=i(33501),f=i(69060),m=(0,s.defer)((()=>(0,n.mkLogger)("writeLicense")));async function p(e,t){return(await(0,o.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,f.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof h.L))}async function g(e,t,i){if(null!=t)if((await p(t,i)).some((t=>t.cmp(e)>=0)))m().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,a.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,c.broadcastEvent_)("reloadLicenses"),m().info("saveIfBetter(): wrote to "+i),i}catch(e){return void m().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,f.vok)(e,"candidate",t);if(null==i)return m().error("!ok",e);await g(i,(0,u.libraryDataDirPosixFile)()?.join((0,f.k)().d),t),await g(i,(0,r.map)((0,l.configDir)(),(e=>d.BaseFile.for(e).join((0,f.k)().d))),t),await f.m.refresh()},t.licensesInDirectory=p,t.saveIfBetter=g},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const s=i(11944),r=i(88491),n=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),b=i(92781);function S(e=10*r.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-r.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*r.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,s.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-r.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const s=i(47261),r=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,s.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:s})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const s=i(4866),r=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,s){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:s})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,s.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const s=i(39938),r=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,s.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const s=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:s,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const s of this.loggers())s.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const s=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,s.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const s=i(4866),r=i(27998);t.DefaultLogFormatter=(0,s.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,s.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:s})}}},7258:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),s.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,s,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,s,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(s){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:s})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}s=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const s=i(49411),r=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,s.join)(e??n.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const s=i(4866),r=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,s.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:r.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const s=i(59694),r=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,s.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const s=i(4866),r=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,s.lazy)((()=>new n(r.LogLevels.warn))),t.defaultLogLevel=(0,s.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],s.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,s,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const s=i(88491),r=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*s.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const s=i(11944),r=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,s=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,s).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-s).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,s.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(s.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),r.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,s,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,r,!0,"f")})),this.stream.on("end",(()=>{u(this,r,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,r,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,r,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,s,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,s,"m",l).call(this),t}},r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=function(e){if(null===e)u(this,r,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const s=i(87561),r=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),E=i(3955),D=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),A=i(98968),O=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,A.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,A.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,s.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,A.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,A.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const s=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(s,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:s,end:i}),(e=>(0,A.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const s=i(55413),r=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new s.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),E=i(83837),D=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),A=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,s){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:s})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),s.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,s,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,s,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,s);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=s&&(r.meta=(0,I.prepMeta)(s)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,A.recentLogEntries)()),(0,A.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,r=new WeakMap,s=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,s,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,s,"m",a).call(this,e,t),c(this,s,"m",u).call(this))},l=async function(){await c(this,s,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,s,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,s,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const s=i(47261),r=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,s.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:s})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const s=i(39938),r=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,s.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),s=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&s.push({...t,from:i})}return s},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const s=i(4866),r=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,s.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,s.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const s=i(49411),r=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,s.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,n.map)((0,b.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const E=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const s=i(4785);t.writeRecentLogEntries=function(){return(0,s.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const s=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...s),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...s]),i}}constructor(e=20){s.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(s=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,s,"m",r).call(this,-1)}get p29(){return n(this,s,"m",r).call(this,-.5)}get p38(){return n(this,s,"m",r).call(this,-.25)}get p84(){return n(this,s,"m",r).call(this,1)}get p98(){return n(this,s,"m",r).call(this,2)}get p99(){return n(this,s,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const s=i(11944),r=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),s=[];for(;e>0;)s.unshift(e%i),e=Math.floor(e/i);return s}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,s.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),s=this.dims.map((e=>e.max)),r=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):s[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),s=this.dims.map((e=>e.max));for(let r=0;r(i[e]+s[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,r.min=n):r.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,s.sum)(e,((i,s)=>t(i,s)?Math.pow(2,e.length-s-1):0))}},31359:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ETA=void 0;const s=i(11944),r=i(88491),n=i(19067),a=i(75556),o=i(7162),l=i(70283),u=i(60346),c=i(6667);t.ETA=class{constructor(){this.remainingMs=new u.Average(10),this.logger=(0,o.mkLogger)("ETA")}push(e){(0,l.mapGt0)(e,(e=>this.remainingMs.push(e)))}clear(){this.remainingMs.clear()}avg(){return(0,c.avg)((0,s.compact)([this.remainingMs.weightedSampleAvg,this.remainingMs.sampleMode]))}fmtEstimate(e=1){return(0,l.mapGt0)(this.avg(),(t=>{const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const s=i(59694),r=i(89965);t.kmeans=function(e,t,i){const n=r(e,t,i);return{...n,centroids:(0,s.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const s=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,s.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,s.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return r(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const s=i(11944),r=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,s){const r=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,s){const n=new a.Average;return l(t,i,s,(t=>(0,r.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,s){const n=[];return l(t,i,s,(t=>(0,r.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,s.range)(r,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,s=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:s/2}),u(e,t,{col:0,row:0},{col:i/2,row:s/2}),u(e,t,{col:0,row:s/2},{col:i/2,row:s}),u(e,t,{col:i/2,row:s/2},{col:i,row:s})];return(0,n.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,s=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:s/2}),c(e,t,{col:0,row:0},{col:i/2,row:s/2}),c(e,t,{col:0,row:s/2},{col:i/2,row:s}),c(e,t,{col:i/2,row:s/2},{col:i,row:s})])},t.greatestHalf=function(e,t){const i=t.col,s=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:s/2}),d(e,t,{col:0,row:0},{col:i/2,row:s}),d(e,t,{col:0,row:s/2},{col:i,row:s}),d(e,t,{col:i/2,row:0},{col:i,row:s})];return(0,n.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const s=[];return l(e,t,i,(e=>s.push(e))),s},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,s.stepRange)(0,t.row,u,(i=>(0,s.stepRange)(0,t.col,o,(s=>(c.clear(),l(t,{col:s,row:i},{col:s+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const s=i(59694),r=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,s){const[r,n,a,o,l]=(0,t.factors)(e),u=(r*i*i+n*i)%s,c=(a*i+o)%s;return Math.round((u*c+l)%s)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,s){const[r,n,a,o,l]=(0,t.factors)(e);return`(((${r}*${i}*${i}+${n}*${i})%${s})*((${a}*${i}+${o})%${s})+${l})%${s}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,s,r,o,l,u,c,h]=d(e%a.SeedCount),f=[i/s,r/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:r.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,s.sortBy)(e,((i,s)=>c(t,s,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,s.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const s=i(6005),r=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const s=[];if(0===t)s.unshift(0);else for(;t>0;)s.unshift(t%e),t=Math.floor(t/e);for(;s.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let s=e;for(;s>u;)t.push(Number(s%i)),s/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,s)=>{i+=e<<8,t[s]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let s=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;s=s*i+BigInt(e)}return t?BigInt(-1)*s:s}randomChars(e){return this.encodeBuffer((0,s.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const s=this.normalizeToken(e),r=this.normalizeToken(t);return s.length>=i&&s===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const s=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,s.toInt)(e)]??(0,r.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const s=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,s.normalizeRotation)(t)?e:new r([...e]).rotate(t).m};class r{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const s=i(6005),r=i(3331);function n(){const e=(0,s.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,r.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,s=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(s+=e)}i++}return s}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){s.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==n(this,r,"f")?e:n(this,r,"f")*n(this,s,"f")/(n(this,s,"f")+1)+e/(n(this,s,"f")+1),"f"),a(this,s,(t=n(this,s,"f"),++t),"f"))}get mean(){return n(this,r,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,s=0;for(const r of e)(0,u.isNumber)(r)&&(s++,i+=(r-t)*(r-t));return i/s}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let s=0;s(1-t)*e+t*(i+a*(e-r)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,s=v(t,((t,s)=>(t-i)*(s-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:s/r}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const s of e)i=null==i?s:i*t+s*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let s=0;se[s]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const s=i(65628),r=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,s.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,s.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=s(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},10309:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.request=void 0;const r=s(i(22286)),n=i(39938),a=i(66776),o=i(9678),l=i(70283),u=i(42041),c=i(79141),d=i(53719);t.request=async function(e,t={}){return null==t.headers&&(t.headers={}),(0,n.blank)(t.headers["user-agent"])&&(t.headers["user-agent"]=o.AppName+" v"+u.version),new Promise(((i,s)=>{const n=r.default.request(e.toString(),t);n.setTimeout((0,a.orElse)(t.timeout,(0,d.commandTimeoutMs)()),(()=>{s(new c.WrappedError("Timeout fetching <"+e+">",{doNotSend:!0,retriable:!0}))})),n.on("response",(e=>{const t=[];e.setEncoding("utf8"),e.on("data",(e=>t.push(e))),e.on("end",(()=>{i({ok:(0,l.within)(200,399,e.statusCode),headers:e.headers,body:t.join(""),statusCode:e.statusCode,statusMessage:e.statusMessage})}))})).on("error",(e=>{s(e)})),(0,a.map)(t.body,(e=>n.write(e))),n.end()}))}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const s=i(70612),r=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,r.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,s.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,r.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,s.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,r.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const s=i(30604),r=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await s.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?s.promises.reverse(e):s.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const s=i(39938),r=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(s.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const s=i(11944),r=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,s.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const s=i(87561),r=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,s.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const s=i(49411),r=i(4866),n=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,n.toS)(__filename).includes((0,s.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const s=i(43383),r=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,s.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,s.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=s(i(70612)),n=s(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=s(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const s=i(39938),r=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,s.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const s=i(4866),r=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,s.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],s=[],r=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?s.push(t):r.push(t)}return{accepted:i,rejected:s,notApplicable:r}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,n.entries)(i))try{if(!1===await s(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:s}){const{accepted:n,rejected:a}=await u.explain(e,...s);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const s=i(61570),r=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const s=i(11944),r=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,s.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const s=i(4866),r=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,s.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,s.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const s=i(87748),r=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,s.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const s=i(75556),r=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,s.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,s.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const s=i(5712),r=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new s.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new s.Task(e,((i,s,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),s,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const s=i(84253);t.AggregateTypes=(0,s.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const s=i(84253);t.AssetFileSortCriteria=(0,s.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const s=i(39938),r=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const s=i(39938),r=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(s.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const s=i(84253);t.ColorDistanceFunctions=(0,s.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const s=i(42885),r=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.encodeDuration,fromEnv:s.decodeDuration})}get valueOrDefault(){return(0,s.decodeDuration)(super.valueOrDefault)}get value(){return(0,s.decodeDuration)(super.value)}set value(e){super.userValue=(0,s.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,s.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:s.encodeDuration,fromEnv:s.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,s.decodeDuration)(this.defaultValue)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const s=i(38625),r=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,r.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,r.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,s.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const s=i(4866),r=i(39784),n=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,s.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const s=await e.resolve_(),n=await t.resolve_();if(null==s||null==n||n.nativePath===s.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:s?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+s.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await s.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=s.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=s.join("licenses"),t=n.join("licenses");for(const s of(0,r.toA)(await e.childFiles())){const e=t.join(s.base);if(await e.notExists())try{await s.copyFile_(e),i.info("Copied license "+s.base)}catch(e){i.warn("Failed to copy license "+s.base,e)}}}const a=n.join("old");try{const e=await s.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const s=i(4866),r=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,s.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const s=i(39938),r=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,s.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:s.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const s=i(84161);class r extends s.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const s=i(42748),r=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>s.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const r=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const s=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,s.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const s=i(4866),r=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,s.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),s=this.envValue??t;return null!=s&&(i[this.key]=this.opts.toEnv(s)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),s=this.toEnvValue(t);return null!=s&&(i[this.key]=s,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const s=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+s],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const s=i(84253);t.SettingCategories=(0,s.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const s=i(5712),r=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),E=i(7560),D=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),A=i(51053),O=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Q=i(29712),Y=i(26764),Z=i(48995),X=i(18947),ee=i(92438),te=i(22130),ie=i(95888),se=i(7043),re=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new se.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new se.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new se.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new s.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new se.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Y.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Q.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:A.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new se.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,O.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new se.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new se.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new se.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new se.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,O.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Z.ColorDistanceFunctions.ciede2000,strEnum:Z.ColorDistanceFunctions}),dominantColorKmeansRuns:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:X.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Y.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new se.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Q.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new se.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new se.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const s=i(4866),r=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,s.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),E=i(98462),D=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),A=i(95699),O=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,s.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(O.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return X(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,s.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Q()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Z()},t.libraryHasSettings=(0,s.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",H),(0,T.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const s=await e.clear().isNonEmpty(),r=s?e.wip():e;if(await async function(e,i){const s=[(0,g.padding)("#",80)];s.push(...se("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),s.push("","");let r="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,s.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),s.push(...e.toTomlLines()),s.push("","")}await e.writeText_("\n"+s.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(r,i),j().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:s}),s){const t=await(0,R.readTomlFile_)(r),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(j().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function Q(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Y(e){return X(z(e))}async function Z(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const s=await(0,R.readTomlFile_)(e);if(null==s)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,r.compact)((0,p.entries)(s).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,s.lazy)((()=>P.version)),t.writeSystemSettings_=Q,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=ee;const te=(0,s.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function se(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Q()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...se("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...se("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...se("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...se("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let s="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...se((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const s=i(49411),r=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",s.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const s=i(84161);class r extends s.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const s=i(11944),r=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,r.stringify)((0,s.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,s.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const s=i(39938),r=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,s.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const s=i(49411),r=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,n.configDir)(),(e=>(0,s.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const s=i(84253);t.TagInferenceSettingValues=(0,s.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const s=i(81627),r=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,s.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const s=i(39938),r=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,s.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,n.stringifyPretty)(t);return(0,s.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,s.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const s=i(87748);t.valueToS=function(e){return(0,s.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const s=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,s.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const s=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,s.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,s.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),E=i(54809),D=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),A=i(43414),O=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(A.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,s.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?A.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:A.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),s=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:s}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:s}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const s of t){let t=e[s],r=s;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(r))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[s]?.rawValue})}}const s=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==s)return;const r=i.filter((e=>(0,u.eql)(e.date,s.date)||e.precisionMs<=s.precisionMs&&(0,w.datedOverlap)({a:e.date,b:s.date,aPrecisionMs:e.precisionMs,bPrecisionMs:s.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:s,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(A.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(A.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(A.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const s=await e.mtimeMs();function r(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:s,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!A.Settings.usePathsToInferDates.valueOrDefault||!A.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:A.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,A.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,A.Settings.capturedAtTagsFallback.values))??(n?void 0:r("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:r("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:r("bname",q(e,t)))??(n?void 0:r("path",H(e)))??(A.Settings.useStatToInferDates.valueOrDefault?r("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,A.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const s=i(84253);t.DateTagFormats=(0,s.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const s=i(75556),r=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,s.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),n=s(i(49411)),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),E=i(21084),D=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),A=i(2023),O=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Q=i(91854),Y=i(54988),Z=i(27446),X=i(84685),ee=i(36062),te=i(15465),ie=i(68107),se=i(26352),re=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const s=i??await(0,te.readMimeType)(e),r=await e.sidecar(),n=(0,Z.isImageMimeType)(s)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Z.isVideoMimeType)(s)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:s,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const s=D.PosixFile.for(e);if(s.isSidecar()&&(i=!1),!await s.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(s.nativePath),void ne().debug("readRawTags("+s+"): invalid file, returning null.");const r=await(0,t._readRawTags)(s.nativePath);if(null==r||!i)return r;ne().trace("readRawTags()",{pf:s,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await s.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,r.tz)]);for(const e of await s.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Z.normalizeMimetype),...r},o=[];for(const[e,i]of n){if(null==i)continue;const s=await i;if(null==s)continue;const r=(0,f.omit)(s,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(s.History)),(0,A.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,A.assignNullishFields)(a,a.inferred),a.Rotation=(0,X.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:s,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,s=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Z.normalizeMimetype);if((0,u.blank)(s))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof r.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,Y.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,Y.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Q.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:s,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,A.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,X.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const s=new h.MultiMap;for(const[r,n]of(0,f.entries)(t)){const t=await me(e,r,i);s.add(t.nativePath,[r,n])}for(const[t,i]of s.entriesArray()){const s=D.PosixFile.for(t),r=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:r}),await le().write(s.nativePath,r,await fe(s)),L.Settings.overwriteOriginal.valueOrDefault||await he(s),s.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,s=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==s)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)}),s.MIMEType=(0,u.mapNotBlank)(s.MIMEType,Z.normalizeMimetype),s.GPSDateTime??(s.GPSDateTime=(0,P.concatDateTime)(s.GPSDateStamp,s.GPSTimeStamp));for(const e of(0,f.keys)(s)){const t=s[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete s[e])}const r=(0,l.compactBlanks)([s.Error,...s.errors??[],s.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(s.problems=r),ae&&(s.__instance=(0,F.safeUUID)()),s}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,s=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,n.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}s.push([a,(0,l.gt0)(o)?o:u])}var r;return b(s)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:s,parser:r}){const n=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+s+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,s.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const s of t)e.set(s,i)}return e})),t.Tag2Synonyms=(0,s.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const s=_(e),n=_(i);if(null==s||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(s),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=s[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:s[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const s=i(39938),r=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,s.blank)(e)||n.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const s=i(4866),r=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,s.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const s=i(84253);t.ExtTypes=(0,s.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const s=i(4866),r=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,s.lazy)((()=>{const e={};for(const[i,s]of(0,o.entries)(t.AllFiletypes))for(const t of s)e[t]=i;return e})),m=(0,s.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,s.lazy)((()=>(0,r.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,s.lazy)((()=>(0,r.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,s.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:s}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,s);for(const i of t.OldBrowserMimetypes)for(const s of t.AllFiletypes[i]??[])e.add(s,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const s of t.AllFiletypes[i]??[])e.add(s,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),s=(0,c.normalizeExt)(t);return null!=i&&null!=s&&(i===s||(p(i)?.includes(s)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:s.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,s]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=s);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function A(e,i,s){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...s??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:s,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:s});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,n.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>s.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const s=F(e);(0,o.blank)(s.nativePath)||(0,P.eqlNameWithoutExt)(s.nativePath,i)?u[t]=s:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,s){const r=D(t.Actions.infer,s),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(s):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:n}),A(i,r,n)},t.ensureHistoryRecords=A},92330:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=s(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),s=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:s,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const s of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[s]);if(null==r||(0,h.isValidDate)(r))continue;const n=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+s+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const s=i(889),r=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),n=s.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??s.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const s=i(84253);t.KeywordReparentingStrategies=(0,s.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const s=i(889),r=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof s.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const s=M(e.Categories);null!=s&&t.push(...s)}for(const s of i){const i=(0,c.pluckDeep)(e,s)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,s.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),s=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&s.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&s.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&s.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&s.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&s.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of s){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(s,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const s=i(4866),r=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const s=e.replace(t,i);return s===e?e:h(s,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,s.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const s=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=s)return s[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,r.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const s=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==s?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:s,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:s.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let s=i?.[e];const r=[];var l;null!=s&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>r.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=s&&s!==i.priorValue&&s!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(s=i.newValue,r.push(`Revision@${i.createdAt}`));return null==s?void 0:{value:s,source:r}}{const e=(0,h.toA)(s);for(const i of t)if("add"===i.op&&null!=i.newValue)r.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){r.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:r}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const s=i(39938),r=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,s.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,s.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,s.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,s.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const s=i(84253);t.NameTagFormats=(0,s.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const s=i(84253);t.NameTagOrders=(0,s.strEnum)("western","eastern")},65308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(66776),l=i(11254),u=i(39784),c=i(7162),d=i(1058),h=i(91464),f=i(6667),m=i(43414),p=(0,s.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Zโ€˜โ€™']+[-A-Zโ€˜โ€™']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),s=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,r.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function M(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(M(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,r.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,r.mapNotEmpty)((0,r.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,r.mapNotEmpty)((0,r.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,r.compactBlanks)(t.split(/\s+/)),T=l.length,E=b.length;if(_.length>0)if(0===T&&E>0)l.push(..._);else if(0===E&&T>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:s,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,r.uniq)((0,r.compactBlanks)(e).filter((e=>null==b.exec(e))))}function M(e){let t="";for(const i of(0,r.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),s=M(t.givenNames);return(0,r.compactBlanks)((0,r.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([s,e]):_(t,s,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const s=i(33714),r=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,s.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,s.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,s.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,s.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const s=i(66776),r=i(75556),n=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,s.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const s=i(4866),r=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,s.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const s=i(11944),r=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,s.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,s.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const s=(0,a.commonPrefixIgnoreCase)(e,i);if(s.length<8)return!1;function n(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(s.length)),l=n(i.slice(s.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const s=i(4866),r=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,s.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,s.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const s=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,s,await(0,h.rawInfo)(e));const n=S(i,s);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const s=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==s)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:s}});const r=(0,a.maybeDimSwap)(s,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:s,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const s=i(82798),r=i(61473);t.tag_fts_root=function(e){const t=(0,s.toS)(e).indexOf(r.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,s.toS)(e).split(r.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),E=i(75123),D=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),A=i(96593),O=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of s){const s=(0,L.extractMakeAndModel)(await(0,A.readRawTags)(t));if((0,f.definedAndNotEql)(s.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:s});else if((0,f.definedAndNotEql)(s.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:s});else if(null!=s.Make&&null!=s.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:s,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),s=await z(t?.older);return null==i||null==s?void 0:{before:i,after:s,index:i.index,slots:i.index+s.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),r=(0,D.findFileIndex)(e,s);if(r<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[s.slice(r-2*t,r),s.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,A.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==s.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const s=await e.stat();if(null!=s){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:s[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:s}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:s}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const s=i[e];if(null!=s&&!0===(0,v.datedOverlap)({a:t,b:s}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(s)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,s.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,s.last)(e)):(0,s.last)(g(e))}function w(e,t){if((0,s.isEmpty)(e)||(0,s.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,s.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,s.uniqBy)((0,l.toA)(e),(e=>(0,s.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,s.compact)(t).map((e=>y(e))));return(0,s.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(s.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const s=i(11944),r=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,s.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const s of i){const i=(0,a.toS)(e[s]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,s.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,r.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const s=i(49411),r=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,s,r,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(s??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:s,query:r,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===s?s=this.path:null===s&&(s=g),void 0===r?r=this.query:null===r&&(r=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&s===this.path&&r===this.query&&n===this.fragment?this:new S(t,i,s,r,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const s=i[2]||g,r=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===s&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(s,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(s.win32.join(T(e,!0),...t)).path:s.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,s=-1;for(let r=0;r=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==s&&(i+=encodeURIComponent(e.substring(s,r)),s=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[n];void 0!==t?(-1!==s&&(i+=encodeURIComponent(e.substring(s,r)),s=-1),i+=t):-1===s&&(s=r)}}return-1!==s&&(i+=encodeURIComponent(e.substring(s))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let s="";const{scheme:r,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(s+=r,s+=":"),(l||"file"===r)&&(s+=y,s+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?s+=i(t,!1):(s+=i(t.substr(0,e),!1),s+=":",s+=i(t.substr(e+1),!1)),s+="@"}e=l.indexOf(":"),-1===e?s+=i(l,!1):(s+=i(l.substr(0,e),!1),s+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}s+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>s+="?"+e)),o&&(s+="#",s+=t?o:M(o,!1)),s}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const s=i(4866),r=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,s.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),s=(0,c.toURI)(t);return i.scheme===s.scheme&&i.authority===s.authority&&f(i.path,s.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const s=i(49411),r=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,s.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),s=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(s.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(s.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?s.win32.sep:s.posix.sep,n=(0,r.notBlank)(t)&&!t.includes(i);if(n&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const s=i(11944),r=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,s.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),s=t.join(i);if(s.isFileSync())return s.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return s.nativePath}},30848:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),s=i[0];if((0,o.blank)(s))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,s)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const s=i(39938),r=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,s.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const s=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(s.version)},t.baseVersion=()=>[s.versionMajor,s.versionMinor,s.versionPatch].join("."),t.versionMajorMinor=s.versionMajor+"."+s.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const s=i(10912),r=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof s.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,s.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,s.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof s.SemVer?e:(0,s.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const s=i(84253);t.UpdateChannels=(0,s.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const s=i(11944),r=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,s.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const s=i(3874),r=i(55412),n=i(46573);t.currentVolumeRoots=(0,r.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const r=(await(0,s.nativePath2uri)(i.mountpoint,i))?.toString();null!=r&&e.push(r)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const s=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,s.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const s=i(4866),r=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),s=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||s||r);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:s,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,s.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],s=m(e["1024-blocks"])??0;if(0===s)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,n=m(e.Available)??0;if(0!==r||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?r+n:s,used:r,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:s,used:r,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const s=["-k","-P"];if(!0===e&&s.push("-l"),s.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",s,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,s.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await A()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),s=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:s,status:i},meta:{input:e}});var n}async function A(){const e=(0,r.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(k)),s=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(s).map(I)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=A},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),E=i(53719);t.isGioSupported=(0,s.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,s.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const s=await k(i.mountpoint);return null==s?i:{remote:!0,...i,...s}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),s=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(s,(e=>e.hostname)),remoteShare:(0,u.opt)(s).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const s=i(4866),r=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,s.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,s.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),s=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==s)return;const n=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const r=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...r,...n},u=s?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,s.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,s.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),s=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=s?{used:i,available:s,size:i+s}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const s=i(55543),r=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,s.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),E=i(43414),D=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),A=(0,s.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function O(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){O(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,s.lazy)((async()=>{E.Settings.libraryDir.watchLater(O),E.Settings.scanPaths.watchLater(O),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,s.lazy)((()=>{}));t.mountpoints_=(0,s.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,s.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],s=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,s):i.includes(s)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),O()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,s.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,s.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=T){if(g.isLinux)try{const s=await(0,f.readLines_)(e),n=(0,r.compact)(s.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,s])=>{const r=t(e),n=await i(s);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&n,meta:{fs:e,mp:s,fsOK:r,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,s.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const s=i(4866),r=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,s.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const s=i(4866),r=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,s.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],s=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(s)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const s=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,s.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,s.blank)(i.remoteHost)&&!(0,s.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,s.blank)(e)&&!(0,s.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const s=i(11944),r=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,s.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,s.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(s=>({mountpoint:(0,y.ensureSuffix)(s[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const s=i(88491),r=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/s.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,s.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),s=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=s)return P().tap({msg:"Serving UUID from "+t,result:s,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=s(i(70612)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),E=i(91464),D=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),A=i(20902),O=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Q=i(55412),Y=i(11142),Z=i(71820),X=i(32421),ee=i(92002),te=i(76019),ie=i(53719),se=i(27127),re=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const s=i.get(e);null!=s&&(0,p.gt)(s.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Q.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Q.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const s=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:s,os:ne}))),n=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const s=e.join(t+".json");try{await s.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:s.nativePath,vol:i}),await s.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),s=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,s))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:n}),r||n?void 0:e}async function pe(e,i){const s=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(s))return;const r=await(0,R.actualPath)(s);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const s=t.find((e=>e.mountpoint===i));if(null!=s)return re().debug("bestVolumeForPath()",{nativePath:r,result:s.mountpoint,src:e.name}),s}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const s=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(s))return;const r=s.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const n=await(0,U.friendlyname)(e);return(0,D.asyncFind)(s,(async e=>(0,E.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),s=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:s.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Q.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,O.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,O.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,O.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,se.addVolumeUUIDs)(i);const s=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:s}),s.forEach(ce),await fe(s),Object.freeze(s)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,s.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,s.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const s=i(84253);t.HelmetPlugins=(0,s.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const s=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,s.within)(200,299,e),success:e=>(0,s.within)(200,299,e),redirect:e=>(0,s.within)(300,399,e),clientError:e=>(0,s.within)(400,499,e),serverError:e=>(0,s.within)(500,599,e),error:e=>(0,s.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const s=i(11254),r=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?s.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,r.compactBlanks)([s.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const s=i(4866),r=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,r.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,s.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),s=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,r.isEmpty)(s))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(s));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const s=i(49411),r=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,s.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const s of e)s.lengthe.includes(t)));if(null!=t)return t;for(let t=0;ts.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const s=i(39938),r=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,s.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,r.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const s of e)t+=i[s]?.[0]??s;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=s(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.availableCpus=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),b=i(91641),S=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),E=i(59387),D=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{D().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)},t.availableCpus=function(){if(_.Settings.cpuBusyPercent.valueOrDefault<=0)return;const e=x.instance().idlePct();if(null==e)return;const t=Math.floor((0,T.cpuInfo)().length*(_.Settings.cpuBusyPercent.valueOrDefault/100));return Math.floor(t*(e/100))};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,s,"m",o).call(this),intervalMs:((0,E.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:b.EndableRanks.first}),s.add(this),r.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,r,"f").push(e))),l(this,s,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,r,"f").sampleAvg??F()}}t.CpuUsage=x,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,r,"f").push(e)},o=function(){l(this,s,"m",a).call(this,F());const e=new C;l(this,s,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const s of e)t+=s.times.user+s.times.nice+s.times.sys+s.times.irq,i+=s.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,s=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(s)?Math.round(t/s*100):void D().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+S.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:s})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},76052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const s=i(4691),r=i(44606),n=i(11053);t.doNotRun=function(e){return null!=o(e)};const a=["error","no-library","stop-sync"];function o(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,n.isTooBusy)())return"system is too busy";const t=(0,r.getRemoteOrLocalHealthSummarySync)();return null!=t&&a.includes(t.level)?t.level+": "+t.msg.join("\n"):void 0}t.whyDoNotRun=o},21003:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=s(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const s=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(s))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([s,i]),meta:{freemem:e,totalmem:t,cgroupMem:s}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const s=i(79015);let r=!1;function n(){r&&(r=!1,(0,s.ee)().emit("clearCache"),(0,s.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?n():r||(r=!0,(0,s.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const s=i(4866),r=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,s.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,s.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,s.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,s=b();if(1!==s){const e=t;t*=s,y().warn("Recent timeouts! Throttling down.",{penalization:s,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:s,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,s.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,s.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const s=i(5712),r=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new s.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},84213:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(5712),o=i(79378),l=i(4866),u=i(7162),c=i(79015),d=i(51081),h=i(24409),f=i(11944),m=i(16475),p=i(87748),g=i(75556),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,s,"m",r).call(this,e))),s.add(this),this.request=e}}t.RequestTask=v,s=new WeakSet,r=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},29144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=t.workerMethodTimeouts=void 0;const s=i(4866),r=i(92585),n=i(61570),a=i(20636),o=i(12374),l=i(7162),u=i(55568),c=i(4691),d=i(49379),h=i(84571),f=i(43414),m=i(59387),p=i(98023),g=i(84213),y=i(48392),v=i(48011),w=(0,s.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let b=0;const S=[[v.WorkRequestMethods.buildAssetPreviews_,f.Settings.taskTimeoutMs.valueOrDefault]];async function P(e,...i){let s=(await(0,y.WorkerCluster)()).t;if(s.ended){if((0,c.ending)())return w().warn("onChild(): cluster is ended, running task myself",{method:e,args:i}),v.WorkerFunctions[e](...i);w().warn("onChild(): cluster ended unexpectedly. Restarting.",{method:e,args:i}),s=(await y.WorkerCluster.refresh()).t}const n=(0,t.workerMethodTimeouts)().get(e)??(0,h.statTimeoutMs)(),o={id:b++,method:e,args:i};return(0,r.retryOnReject_)((async()=>{const e=new g.RequestTask(o),t=s.enqueueTask(e);return(0,a.thenOrOnTimeout)(t,n/3,(()=>{w().warn("soft timeout servicing work request",{request:o,timeoutMs:n}),(0,p.onTimeout)()})),(0,a.thenOrTimeoutError)(t,n)}),{maxRetries:f.Settings.maxRetries.valueOrDefault,timeoutMs:n,retryDelay:f.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,d.isRetriableError)(e)})}function M(){for(const e of(0,n.values)(v.WorkerFunctions))e.setShim(void 0)}t.workerMethodTimeouts=(0,s.lazy)((()=>new Map(S))),t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,m.singleThreadMode)()||(0,u.isWorkerService)())w().warn("in single-threaded mode"),M(),await((await y.WorkerCluster.prior())?.end());else for(const[e,t]of(0,n.entries)(v.WorkerFunctions))t.setShim((t=>P(e,t)))},t.clearShims=M},48011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const s=i(75556),r=i(61570),n=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,n.strEnum)(...(0,r.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)}},48392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerCluster=t.workerClusterPriorEnd=void 0;const s=i(5712),r=i(13056),n=i(4866),a=i(7162),o=i(38307),l=i(91641),u=i(69317),c=i(95237),d=i(53525),h=i(51081),f=i(24409),m=i(29663),p=i(59387),g=i(88491),y=i(87748),v=i(75556),w=i(2934),b=i(82798),S=i(24905),P=i(94845),M=i(43414),_=i(75153),T=i(941),E=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.WorkerCluster.prior())?.t.closeChildProcesses()},t.WorkerCluster=(0,n.lazy)((async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return E().throw("Could not find worker.js");E().info("worker.js found at "+e);const t={id:-1,method:"ping",args:[{}]},i=new s.BatchCluster({processFactory:async()=>(E().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,T.workerEnv)()})),...(0,r.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,P.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:S.ChildServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,_.cpuCount)(),e??(0,p.maxCpus)());return E().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new r.BatchClusterObserver("worker",i,l.EndableRanks.first)}))},941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const s=i(10347),r=i(43414),n=i(32421),a=i(38625),o=i(61570);t.workerEnv=async function(){const e={};for(const t of(0,o.values)(r.Settings))t.hasValue()&&!(0,a.isTrue)(t.opts.transient)&&t.addToEnvMaybe(e);return r.Settings.libraryDir.addToEnv(e),r.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,s.childEnv)({overrides:e,forWorker:!0})}},45766:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=s(i(97742)),n=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const s=i(59694),r=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const s=e[t];return e.splice(t,1),e.splice(i,0,s),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const s of e)if(null!=s){const e=t(s);null!=e&&(0,o.getOrSet)(i,e,(()=>s))}return[...i.values()]}function P(e,t,i=1,s=(e=>e)){const r=[];if(et;n-=i)r.push(s(n));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,s.sortBy)(e,g),r=(0,s.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const s=e.map(i);for(const r of t){const t=i(r);s.includes(t)||(e.push(r),s.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let s=0;s0)return e.splice(s,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,s.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,s.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const s of e)if(null!=s){const e=t(s);null!=e&&i.set(e,s)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const s of e)null!=s&&i.every((e=>!t(s,e)))&&i.push(s);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,s)=>e+(t(i,s)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,s)=>e+t(i,s)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const s=Math.round(i);if(s<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,s=t.primitiveValueOfOrElse){const r=new Set(i.map(s));return e.filter((e=>!r.has(s(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const s=i(11944),r=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const s of e)(0,o.getOrSet)(i,(0,a.stringify)(t(s)),(()=>s));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,s.compact)(e),s.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,s)=>0===s||t(i)>=t(e[s-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const s=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const s=i(47025);t.asPromise=async function(e){const t=await e;return(0,s.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const s=i(88012),r=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const s=(0,c.toS)(e.v);return(0,n.blank)(s)||"1"===s||(i??(i=new URLSearchParams)).append("v",s),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,s.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,s.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,s.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:n,af:l}){if(null==(0,s.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=r.map((s=>m(y({assetId:e,params:t,reducer:i,width:s}),s)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,s.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:s="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===s?80:"m"===s?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const s=i(43947),r=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,s.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,s.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const s=i(66776),r=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,s.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function s(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!s(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=s,t.isDisabled=function(e){return s(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):s(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const s=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,s.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const s=i(11944),r=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const s=Math.floor(e/t.hourMs);e-=s*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(s)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},s=10*i(),r=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,r,s)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/s.ms);e-=n*s.ms,n>0&&(s.ms>=t.dayMs?i:r).push(n+s.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,s.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const s=i(38625),r=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const s=i.get(e)?.get(t);return"boolean"==typeof s?s:null}function a(e,t,i,s){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,s):(r=new WeakMap,r.set(t,s),i.set(e,r))}function o(e,t,i,s){if(null!=i?.comparator)return u(e,t,i,s);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,s){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,s);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,s){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],s);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,s);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,s);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),s);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),s);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const s=[],r=[];return e.forEach((function(e,t){s.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(s.sort(),r.sort(),i)}(e,t,s);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,s)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const s=e.length;if(s!==t.length)return!1;if(0===s)return!0;let r=-1;for(;++r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,s=!1;const r=function(){if(s){if(null!=i)throw i;return t}try{return s=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const s=i(88491),r=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>s.secondMs&&t&&r.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=s.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const s=i(75556),r=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,s.toGt0)(e?.width)??0)*((0,s.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,s.gt0)(e)&&(0,s.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const s=i(85120),r=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,s.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const s=l.get(i);if(null!=s)return s(e,t)??null}for(const i of o){const s=i(e,t);if(null!=s)return s}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,s.uniq)((0,s.compactBlankish)((0,n.flatten)((0,s.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,s.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const s=i(39784);t.flatten=function(e,t=[]){for(const i of(0,s.toA)(e))if(null!=i)for(const e of(0,s.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const s=i(11944),r=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,s.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,s.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const s=i(11944);function r(e,t){return null==(e=(0,s.uniq)((0,s.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const s=i(39938),r=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,s.blank)(e.id)&&!(0,s.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,s.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const s=i(84253);t.ReducerNames=(0,s.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const s=i(84253);t.FitSizes=(0,s.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,s.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const s=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,s.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,s.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(s,r){if((0,isFunction_1.isFunction)(s))return;let n,a,o,l=toJSON(s);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(s===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const s=i(11944),r=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,s.isEmpty)(l))return;const n=await e,o=await i;if(!(0,r.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const s=i();return null!=s&&e.set(t,s),s}},t.deleteIf=function(e,t){for(const[i,s]of e.entries())t(i,s)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const s=i(90957),r=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,s.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,s){return null==e||null==t||null==i?void 0:s(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,s.tot)(i)},t.map2Or=function(e,t,i,s){return o(a(e,t,i),s)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const s=i(11944),r=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,s]of Object.entries(e))t.add(i,...s);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,s.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,s.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const s=i.filter((e=>!(0,n.eql)(e,t)));return 0===s.length?this.store.delete(e):this.store.set(e,s),i.length!==s.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,s.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,s.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,s.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const n=r.length;(0,s.filterInPlace)(r,(t=>e(i,t))),t=t||n!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const s of i)e.add(s,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,s]of this.entries())s.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const s=i(59694),r=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,s.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const s=(0===t?1e-5:t)*(1-i);return m(t-s,t+s,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),s=Math.pow(10,Math.abs(i));return i<0?_(e/s)*s:_(e*s)/s},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,b(t)?_(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,s]=i;null!=e&&void 0!==s&&("object"!=typeof t&&(t={}),t[e]=s)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,s.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,s.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,s.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,s.uniq)((0,s.flatMap)(i,h)))r[e]=b(...i.map((t=>t[e])));return r}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[s,r]of g(t))!0!==i?.omitKeys?.includes(s)&&(null==r&&!0!==i?.assignNullish||(e[s]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const s of i){const i=t[s];void 0!==i&&void 0===e[s]&&(e[s]=i)}return e},t.assignAllFields=function(e,t){for(const[i,s]of g(t??{}))e[i]=s;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,s.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,s.compact)(t.map(e));{const i=(0,s.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,s.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const s of t)void 0!==e[s]&&(i[s]=e[s]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const s of t)void 0!==e[s]&&(i[s]=e[s]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const s of t){const t=e[s];(0,n.notBlank)(t)&&(i[s]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const s of t)if(i(e[s]))return e[s]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const s={};function r(e,t){if(null==t)return;const i=s[e];s[e]=null==i?t:b(i,t)}for(const s of i){const[i,a]=(0,c.splitFirst)(s,"."),o=S(t,i);null!=o?.value&&r(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const s of h(t))((0,l.toInt)(s)??-1)>=0&&r(s,e(t[s],...i));return s},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const r=(0,s.compact)(t.map((t=>e(t,i))));return(0,s.isEmpty)(r)?void 0:{key:r[0].key,value:(0,s.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=S(t,r);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,s.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,s.uniq)(t)},t.maybeCall=function(e,t,...i){const s=e?.[t];return(0,a.isFunction)(s)?s.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),s=p(i);return 1===s.length?s[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class s{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new s(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,s){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>s(this.a,e,t,i)))))))}}function r(e){return e instanceof s||e===t.None}function n(e){return r(e)?e:null!=e?new s(e):t.None}t.Some=s,t.isOpt=r,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const s=i(75556),r=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,r.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,s.toInt)((0,n.toS)(e));return(0,s.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const s=i(75556),r=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,s.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const s=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,s.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const s=i(11944),r=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const s=typeof e,n=typeof i;if(!("string"!==s&&"symbol"!==s||"string"!==n&&"symbol"!==n)){const s=(0,r.toS)(e),n=(0,r.toS)(i),a=s.localeCompare(n);return s[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):s!==n?o.indexOf(s)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const s=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,s.toA)(await e))if(null!=r){const e=await r;if(null!=e){const s=await t(e);null!=s&&i.push(s)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const s=await e;return t(s)?i(s):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const s=i(84253);t.PromiseStates=(0,s.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const s=i(11944),r=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,s){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(s??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const s of o(0,e.length,t))i.push(e[s]);return i},t.pickWeightedRandom=function(e){if((0,s.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,s.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let s=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,s=s.slice(0,r.index)+i(r)+s.slice(r.index+r[0].length);return s}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const s=i(75556);function r(e){if(!(0,s.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,s.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const s=i(84253);t.RunStates=(0,s.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const s=i(84253);t.ServiceNames=(0,s.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const s=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,s.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),s=a(t);return null==i||null==s?void 0:i>s?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const s=i(11944),r=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const s=f();return null!=s?(0,o.sliceIterable)(s.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),s=(0,c.toS)(t);return s.length>0&&i.startsWith(s)?i.slice(s.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),s=(0,c.toS)(t);return s.length>0&&i.endsWith(s)?i.slice(0,-s.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let s=i;s>=0;s--)if(m(e,s).startsWith(t))return s;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const s=(0,c.toS)(e),r=(0,c.toS)(t);return s.length===r.length&&(s===r||s.toLowerCase()===r.toLowerCase()||"function"==typeof s.localeCompare&&0===(i?s.normalize():s).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,s.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const s=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&s.startsWith(t))return e(s.slice(t.length),i);return s},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const s=p(e);return s.length<=t?s.join(""):s.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?s.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const s=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const s=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(s.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=s)return[t];const n=b(t," ",s);if(n>r.length)return[m(t,0,n),...e(m(t,n+1),i)];{const s=t.indexOf(" ",r.length+1);return s>0&&s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const s=i(88491),r=i(61570),n=i(90957),a=i(21669);async function o(e,i,s=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{s&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const n=await o(e,i,r);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,s.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,s=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,s)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(s,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{s(await i())}catch(e){n(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),s(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,s.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:s,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,n.tot)(s):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const s=i(47025);t.tot=function(e){return(0,s.isFunction)(e)?e():e},t.tol=async function(e){return(0,s.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const s=i(11944),r=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,s.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,s]of e.entries())i.set(t,s);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const s=i(39938),r=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const s of e)(0,n.isNumber)(s)&&(i+=s/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,s.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),s=Math.floor(i/3),r=Math.pow(10,3*s),a=d[s];return(0,n.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),s=Math.floor(i/10),r=Math.pow(2,10*s),a=h[s];return(0,n.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,s.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const s=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,s.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const s=i(11448),r=i(82798);t.ua=(0,s.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,s=/\bSafari\b/,r=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,s)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const s=i(66776),r=i(75556);function n(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,s.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},42313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const s=i(84253);t.SyncStatuses=(0,s.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const s=i(84253);t.S=(0,s.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const s=i(59694),r=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,s.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,r.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const s=i(11944),r=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const s=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(s?.get("seed"))){const e=(0,t.urlSeed)().toString();return s?.set("seed",e),s??{seed:e}}return s}function u(e,t,i=!1){const s=c(e,t,i);return(0,o.assembleFullPath)(s.path,s.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,s.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,r.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const s=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,s.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const s=i(11944),r=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,s.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const s=i(87748);t.toS=function(e){return n(e,",")};const r={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==r?e.toString():(0,s.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const s=i(4866),r=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),b=i(43414),S=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),E=i(94332),D=i(63216),k=(0,s.lazy)((()=>(0,r.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,D.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,s.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:b.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,s.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:b.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,s.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(b.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,s.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),A=(0,s.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),O=(0,s.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(b.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,s.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,s.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:b.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,s.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,S.compact)([x(),C(),F(),I(),A(),(0,w.LogDirCleanup)(),O(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,s.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},64303:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceRebuildLibrary=void 0;const s=i(93813),r=i(30690),n=i(89452),a=i(36310);t.forceRebuildLibrary=function(){r.Asset.dbl.runf((e=>e.update({version:0}))),n.AssetFile.dbl.runf((e=>e.update({version:0}))),a.Operation.dbl.runf((e=>e.where({name:a.OperationNames.enqueueAssetFileUpdates,version:s.AssetFileVersion}).orWhere({name:a.OperationNames.enqueueAssetUpdates,version:s.AssetVersion}).delete()))}},49374:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),E=i(46573),D=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),A=i(61570),O=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,s,"f",r)?.rootDir.nativePath,i=!0===a(this,s,"f",r)?.isReadySync(),n=!0===a(this,s,"f",r)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,s,"f",r):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,s,"f",r)),o(this,s,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new s(e),"f",r))}static get priorInstance(){return a(this,s,"f",r)}static endPriorInstance(){const e=a(this,s,"f",r);return o(this,s,void 0,"f",r),(0,l.end)(e)}static async instanceReady(){const e=s.instance();return await(e?.ready),e}static instanceRequired(){const e=s.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,A.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,s=j,n=new WeakMap,r={value:void 0}},93445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const s=i(23872),r=i(31216),n=i(9069),a=i(13222);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,s.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:r.isValidFile}),i}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const s=i(19658),r=i(20902),n=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,r.isEnvTrue)("ENABLE_SENTRY")||s.isProd&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),b=i(91641),S=i(95557),P=i(4691),M=i(52289),_=i(10408),T=i(27519),E=i(49379),D=i(17875),k=i(79015),x=i(12737),C=i(49857),F=i(7157),I=i(85352),A=i(9483),O=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const s=await Z(e);return await(T.ErrorStore.instance()?.maybeSendEvent(s))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Q(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Q(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await X());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function X(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Q,t.sentryExceptionToS=Y,t.annotateEvent=Z,t.mkBreadcrumbs=X,t.logEntryToBreadcrumb=ee;const te=new Map([[A.LogLevels.fatal,"fatal"],[A.LogLevels.error,"error"],[A.LogLevels.warn,"warning"],[A.LogLevels.info,"info"],[A.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),b=i(7162),S=i(33148),P=i(55568),M=i(25516),_=i(38307),T=i(42041),E=i(95557),D=i(4691),k=i(2126),x=i(7383),C=i(70259),F=i(24905),I=i(44731),A=i(20902),O=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Q=i(39938),Y=i(88491),Z=i(43947),X=i(6314),ee=i(66776),te=i(50530),ie=i(82798),se=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{x.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,k.exit)({reason:"exit() event",status:0})))}));class re extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,s,"m",l).call(this))),s.add(this),this.opts=e,r.set(this,void 0),n.set(this,new X.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup()",(()=>m(this,s,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,s,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,r,(0,b.mkLogger)("Service("+this.name+")"),"f"),m(this,s,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,n,"f").promise}get isReady(){return m(this,n,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=re,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,s=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Q.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Q.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new B.WrappedError(e)}),5*Y.secondMs)})),(0,S.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,s,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,n,"f").reject():m(this,n,"f").resolve()}catch(e){console.error((0,O.errorToS)(e)),m(this,n,"f").reject((0,te.toErr)(e)),(0,k.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,O.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,se.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,Z.later)((()=>(0,k.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,r,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,r,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,r,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},13902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const s=i(4866),r=i(7162),n=i(80294),a=i(82341),o=i(43414),l=i(82041),u=i(53719),c=i(46573),d=i(88491),h=i(75556),f=i(17078),m=(0,s.lazy)((()=>(0,r.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const s of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const r=await(0,c.bestVolumeForPath)(s,t);if(null==r)return void m().warn("Can't find volume for "+s+", using default TTL for volumes()");if(r.available{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const s=i(4866),r=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,s.lazy)((()=>(0,r.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},s=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),r=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+s);return e?(await(0,d.writeTextfile_)(r.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+r),r):r}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||ig(this,d,"f").call(this),intervalMs:7*V.secondMs,onEnd:()=>g(this,s,"m",n).call(this),rank:D.EndableRanks.first,endTimeoutMs:M.ShortCommandTimeoutMs}),s.add(this),this.queueNames=e,this._processItem=t,this.processRate=new w.Rate,this.processMs=new A.Average,this.ee=new b.default.EventEmitter,r.set(this,!1),this.recentlyProcessed=new T.TTLArray(V.minuteMs),this.on=this.ee.on.bind(this.ee),this.queues=(0,S.lazy)((()=>H.Queue.ops().upsert((0,j.compactBlanks)(this.queueNames).map((e=>({name:e})))))),this.queueIds=(0,S.lazy)((()=>this.queues().map((e=>e.id)))),this.queueItemCount=(0,S.lazy)((()=>{const e=this.queueIds();return G.QueueItem.dbl.pluckFirstf((t=>t.countDistinct("id").whereIn("queueId",e)))})),u.set(this,(0,S.lazy)((()=>{this.logger.debug("status",this.state())}),(P.isTest?1:30)*V.secondMs)),d.set(this,(0,S.lazy)((()=>setTimeout((()=>{g(this,s,"m",o).call(this),g(this,d,"f").unset(),g(this,s,"m",m).call(this)}),100)))),h.set(this,(()=>g(this,d,"f").call(this))),f.set(this,(0,S.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,N.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,L.isTooBusy)(),whyDoNotRun:(0,R.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.queueItemCount(),freeSlots:this.p.freeSlots()})),(P.isTest?1:30)*V.secondMs)),this.p=new x.Promises(c,i?B.maxConcurrentImports:()=>1),this.p.ee.on("vacancy",(()=>g(this,d,"f").call(this))),this.p.ee.on("drain",(()=>g(this,s,"m",a).call(this))),!0===l&&this.awaitDrain().then((()=>this.end())),(0,I.ee)().on("resume",g(this,h,"f"))}async awaitDrain(){if(this.isDone())return;const e=new U.Latch;this.ee.once("drain",(()=>e.resolve())),g(this,d,"f").call(this),await e.promise}isDone(){return this.ended||g(this,r,"f")}isRunnable(){return!this.isDone()&&!this.p.isFull()}findQueue_(e){const t=this.queues();if((0,z.blank)(e))return t[0];const i=t.find((t=>t.name===e));if(null==i)throw new C.InternalError("WorkQueue: unknown queue name "+(0,W.stringify)(e));return i}enqueueWork(e,t){const i=this.findQueue_(t);this.logger.debug("enqueueWork()",{items:e,queue:i});const s=i.upsertWorkItems(e);return y(this,r,!1,"f"),g(this,d,"f").call(this),s}get recentFileProgress(){return this.recentlyProcessed.map((e=>e.contents))}processedCount(){return this.processRate.eventCount}currentWorkCount(){return this.p.pendingWithName(this.name).length}pendingWorkCount(){return this.queueItemCount()-this.currentWorkCount()}percents(){const e=this.processedCount(),t=this.queueItemCount(),i=(0,q.round)(e/(t+e)*100);return{done:e,todo:t,completePct:i,incompletePct:100-i}}currentQueueItems(){return this.p.payloadsWithName(this.name)}currentQueueContents(){return this.currentQueueItems().map((e=>e.contents))}currentQueueItemIds(){return this.currentQueueItems().map((e=>e.id))}etaMs(){const e=this.processMs.n<=6?void 0:this.processMs.p84;return null==e?void 0:this.queueItemCount()*e}state(){return{...this.p.stats(),isDone:g(this,s,"m",a).call(this),freeSlots:this.p.freeSlots(),currentWork:this.currentQueueContents(),pendingWork:this.queueItemCount(),next10:g(this,s,"m",c).call(this,10).map((e=>e.contents)),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.contents)),isRunnable:this.isRunnable(),...this.percents(),etaMs:this.etaMs()}}doNotStartMoreWork(){return(0,N.isPaused)()||this.p.isFull()||(0,L.isTooBusy)()||(0,R.doNotRun)(this)||0===this.pendingWorkCount()}}t.WorkQueue=$,r=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,s=new WeakSet,n=function(){return(0,I.ee)().off("resume",g(this,h,"f")),this.awaitDrain()},a=function(){if(this.ended)return!0;const e=g(this,r,"f");return y(this,r,0===this.currentWorkCount()&&0===this.queueItemCount()&&0===this.queueItemCount.refresh(),"f"),!e&&g(this,r,"f")&&(g(this,u,"f").refresh(),this.ee.emit("drain")),g(this,r,"f")},o=function(){this.queueItemCount.unset()},l=function(e){e.delete(),this.logger.info("postProcessItem()",{item:e}),g(this,d,"f").call(this)},c=function(e){return G.QueueItem.ops().allf((t=>(t=t.distinct().whereIn("queueId",this.queueIds()).andWhere((e=>e.whereNotIn("id",this.currentQueueItemIds()))).orderBy("id"),(0,q.gt0)(e)&&(t=t.limit(e)),t)))},m=function(){if(this.doNotStartMoreWork())g(this,f,"f").call(this);else{g(this,u,"f").call(this);const e=(0,L.availableCpus)(),t=this.p.freeSlots(),i=(0,O.min)([e,t]),r=g(this,s,"m",c).call(this,i);this.logger.debug("runChunk():",{idleCpus:e,freeSlots:t,availableSlots:i,next:r});for(const e of r)this.p.enqueue({name:this.name,payload:e,l:()=>g(this,s,"m",p).call(this,e)})}g(this,s,"m",a).call(this)},p=async function(e){try{const t=Date.now();await this._processItem(e);const i=Date.now()-t;this.recentlyProcessed.push(e),this.processRate.onEvent(),this.processMs.push(i),this.ee.emit("processed",e,i)}catch(t){(0,F.onError)(this.name+" failed to process item "+e.contents,t)}finally{(0,k.ending)()||g(this,s,"m",l).call(this,e)}}},26367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DropWorkQueuesArg=void 0;const s=i(43414),r=i(38625);t.DropWorkQueuesArg={beforeParse:e=>e.option("--drop-queues","Before starting, all previously-enqueued, incomplete work will be deleted."),afterParse:async e=>{(0,r.isTrue)(e.dropQueues)&&(s.Settings.dropWorkQueues.envValue=!0)}}},12182:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDone=void 0,t.ExitWhenDone="--exit-when-done"},78877:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDoneArg=void 0;const s=i(43414),r=i(38625),n=i(12182);t.ExitWhenDoneArg={beforeParse:e=>e.option(n.ExitWhenDone,"Exit after jobs are completed. Defaults to false unless paths are specified on the command line."),afterParse:e=>{(0,r.isTrue)(e.exitWhenDone)&&(s.Settings.exitWhenDone.envValue=!0)}}},80338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ForceArg=void 0;const s=i(43414),r=i(38625);t.ForceArg={beforeParse:e=>e.option("--force","Deletes prior cached directory metadata, and forces directory contents to be re-scanned."),afterParse:async e=>{(0,r.isTrue)(e.force)&&(s.Settings.forceSync.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const s=i(55568),r=i(85297),n=i(43414),a=i(38625);function o(){return(0,s.isMainService)()||(0,s.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),s=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":s?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,r.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||s||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},50763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const s=i(23830),r=i(38625);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,r.isFalse)(e.filter)&&(0,s.disableAllFilters)()}}},51315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RebuildArg=void 0;const s=i(43414),r=i(38625);t.RebuildArg={beforeParse:e=>e.option("--rebuild","Rebuild your library by re-importing all your photos and videos (slow!) https://photostructure.com/faq/sync-vs-rebuild/"),afterParse:async e=>{(0,r.isTrue)(e.rebuild)&&(s.Settings.forceRebuildLibrary.envValue=!0)}}},64239:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SkipUpdateArg=void 0;const s=i(43414),r=i(38625);t.SkipUpdateArg={beforeParse:e=>e.option("--skip-updates","DANGEROUS: If you want to immediately import specific files or directories and skip any pending library maintenance tasks (like library rebuilds), use this argument. Note that asset aggregation may be incorrect after using this command if there are updates pending."),afterParse:e=>{(0,r.isTrue)(e.skipUpdates)&&(s.Settings.noModelUpdates.envValue=!0)}}},24709:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(91464),o=i(93125),l=i(43414),u=i(96593),c=i(28033),d=i(61473),h=i(11944),f=i(39938),m=i(61570),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,s.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const r=i[0],n=(0,s.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(r)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...r,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...r]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const s=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=s){t.releasedAt=s;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},69258:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const s=i(4866),r=i(7162),n=i(46852),a=i(43414),o=i(61473),l=i(11944),u=i(26588),c=i(30690),d=i(24709),h=i(51832),f=i(18290),m=i(96672),p=i(82355),g=i(7587),y=i(52465),v=i(40399),w=i(83089),b=(0,s.lazy)((()=>(0,r.mkLogger)("curators.AssetTagger")));async function S({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:s,uris:r}){const u=[];t.some((t=>t.nativePath===e.nativePath))||t.unshift(e),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{b().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,g.lensTagFile)(e),(t=>{b().debug("Lens tag for "+e+":",t),u.push(t)})),await(0,n.thenMap)((0,f.dateTagFile)(e,s),(t=>{b().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,w.whoTagFiles)(t)??[];b().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,p.keywordTagFiles)(t,c),(t=>{b().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{b().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(r),(e=>{b().debug("file paths for uris",{uris:r,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{b().debug("Album tags for "+e+":",t),u.push(...t)}));const S=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(y.normalizeTagRoot),o.joinTagPath)),P=await(0,y.tagDeltas)(i,S);return b().info("tagAsset("+e+")",{priorTagPaths:i,after:S,result:P}),P}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();b().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),s=await(i?.posixFile_());if(null==i||null==s)return void b().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:s,doNotSend:!0,fatal:!1});const r=e.getShown();r?.id!==i.id&&(b().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:r?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await S({primaryVariation:s,files:n,priorTagPaths:d,capturedAts:h,uris:l});b().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return b().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),b().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});b().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=S},51832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const s=i(96593),r=i(11254),n=i(11944),a=i(39938);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([r.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,s.readTags)(e))}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const s=i(4866),r=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,s.lazy)((()=>new Intl.DateTimeFormat((0,r.localeSync)(),{month:"short"}))),v=(0,s.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const s=(0,c.bestCapturedAt)(i);return null==s||(0,c.capturedAtSrcFromStat)(s.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(s.date)}},96672:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const s=i(4866),r=i(7162),n=i(61473),a=i(22356),o=i(11944),l=i(49049),u=i(11254),c=i(89452),d=i(9069),h=i(63216),f=(0,s.lazy)((()=>(0,r.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},82355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(1058),o=i(91464),l=i(2073),u=i(46852),c=i(43414),d=i(96593),h=i(28033),f=i(61473),m=i(11944),p=i(59694),g=i(39938),y=i(43947),v=i(1429),w=i(66776),b=i(11254),S=i(82798),P=i(52465),M=i(83089),_=(0,r.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,r.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],r=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))r.push(t);else{const e=(0,S.toS)(t).replace(k,(e=>(i.push(e),"")));r.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=r.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,s.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,r]=(0,s.partition)(x(e),M.isWhoTag),n=(0,v.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...r.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},7587:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const s=i(46852),r=i(43414),n=i(96593),a=i(11254),o=i(11944),l=i(39938),u=i(66776);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(r.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,s.thenMap)((0,n.readTags)(e),c)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const s=i(7162),r=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,s.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...r.Settings.rootTagKeywordsAliases.values,...r.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...r.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...r.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...r.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),s=(0,n.tagDiff)(e,t),a=r.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,s)&&(s.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:s}}},40399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const s=i(4866),r=i(7162),n=i(91464),a=i(46852),o=i(15465),l=i(11944),u=i(39938),c=i(66776),d=i(90957),h=i(11254),f=(0,s.lazy)((()=>(0,r.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,s.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():(0,c.orElse)(m.get(e.trim().toLowerCase()),(()=>(0,n.capitalize)(e)))}t.friendlySubtype=y,t.fixCase=v},83089:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const s=i(4866),r=i(7162),n=i(43414),a=i(96593),o=i(71932),l=i(65308),u=i(61473),c=i(11944),d=i(39938),h=i(1429),f=i(61570),m=i(11254),p=i(39784),g=(0,s.lazy)((()=>(0,r.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),s=i?.peopleNames;(0,c.isNotEmpty)(s)&&t.push(...s)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},18130:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),E=i(88491),D=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class A extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),s.add(this),this.schema=e,this.dbFile=t,r.set(this,0),n.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,s,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const s=new C.Migration(this.schema,this.db,t),r=await s.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:r,migration:s,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,r,(e=l(this,r,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),r=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,s,"m",o).call(this,r),i||await(0,y.dbBackupCold_)(r,e),e.join(this.dbFile.base)}}t.Db=A,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),E=i(94332),D=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,s,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,s,"m",a).call(this)}),s.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),r.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,r,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,s,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,r,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,s,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,r,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,r,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,r=new WeakMap,s=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const s=i(4866),r=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,s.lazy)((()=>(0,r.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const s=await f.PosixFile.forUri(i.uri);if(null==s)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(s.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:s,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+s.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:s}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:s}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let r,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(r=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==r||null==o){const i=await(0,n.getLiveDbDir_)(e),s=await i.db.uri_();r=i.useReplica,r&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:s,useReplica:r})}})),null==o||null==r)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();r&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!r),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:r,libraryDbFile:t,libraryDbBackupDir:s,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const s=i(51498),r=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new s.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const s=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return s.database.open?{sq:i,stmt:s}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:s,stmt:r}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(s));const n=r[i].bind(r);return null==s.bindings?n():n(s.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const s of e){if((0,h.blank)(s)||s.trim().startsWith("--"))continue;this.run({sql:s});const e=(0,m.replaceAll)((0,m.ellipsize)(s,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const s=i(10408),r=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,r.blank)(e)){t._dbSetupErrors.add((0,s.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const s=i(4866),r=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,s.lazy)((()=>(0,r.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const s=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),r=(0,o.compactBlanks)(s.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=s[0],l=s.slice(1),u=n?.id;if((0,o.isEmpty)(r)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:r,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,r[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:r});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),s=(0,a.joinTagPath)([...f,...i]);t._path!==s&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:s}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:s}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:s}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:s}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(s).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const r=s(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,r.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),E=i(43947),D=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),A=i(72537);t.Migration=class{constructor(e,t,i){s.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,s,"m",r).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),r=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(r);return o?await r.bind(I.Migrations)(this.db):await a(this,s,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},s=new WeakSet,r=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const s of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+s.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(s))),await(0,h.thenOrTimeout)(this.applyMigration_(s,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+s.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(s.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,A.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),E=i(85476),D=(0,r.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,s]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,s)?new Date(t,i-1,s):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const r of t){const t=(0,_.toS)(r.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,s.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,s.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),s=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:s});for(const t of s)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const s=i(70403),r=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),E=i(6314),D=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),A=i(9069),O=i(70582),L=(0,r.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const s=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(s,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(s)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,O.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const r=await(0,y.sqliteNativePath_)(),n=await(0,s.thenElapsed)((0,a.stdout_)(r,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,A.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:s=w.Settings.dbWalCheckpointType.valueOrDefault}){if((s=l.CheckpointTypes.getCI(s)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const r="wal_checkpoint("+s+")",[n]=(0,F.toA)(t.pragma(r));return L().info("checkpoint()",{pragma:r,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),s=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${s})`);try{const e=await(0,y.sqliteNativePath_)(),r=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},r),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:r});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[s.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:r});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${s}.`),V(s),L().info(`repairDbFile_(): ${s} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(s),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const s=i(13779),r=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,s.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,r.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const s=i(39938),r=i(89253);function n(e){const t=new r.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,s.blank)(i.name)||(0,s.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const s=i(5853),r=i(43414),n=i(82798);t.withDbSync=function(e,t,i=r.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,s.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=r.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,s.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},30690:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),E=i(87748),D=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),A=i(89452),O=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),s.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),s=await(0,w.readTags)(i),r=await(i?.mtimeMs());null!=i&&null!=s&&null!=r&&e.push({...s,SourceFile:i.nativePath,sourceModifiedTime:r,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?r.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?r.ops().firstf((t=>r.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??r.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return r.ops().count(r.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const s=(0,d.mkLogger)("Asset("+e+").remove()"),n=r.ops().findById(e);if(null==n)return void s.warn("asset not found");const a=n.isActive(),o=n.tagIds();s.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=A.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),A.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),r.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await r.deletePreviews(e)}catch(e){s.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,r,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,r,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,r,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=r.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),A.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),r.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,O.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const s=this.getAssetFiles().find((e=>e.uri===i));if(null!=s)return s;const r=new A.AssetFile;return this.addAssetFile(r),!0!==t?.skipUpsert?await r.upsertIfNeeded_(e):await r.setFile_(e),r}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=r.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),s=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:s})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),s=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(s))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(s)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",s).andWhere({assetId:this.id}).delete())),this.tags=void 0;const r=(0,S.uniq)([...t,...i]).filter((e=>!s.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(r,1),r}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=r.dbl.all(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(A.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof A.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const s=t.id===e.id||t.uri===e.uri;return s&&(this.assetFiles[i]=e),s})));const i=e instanceof A.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const s=Date.now();A.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:s}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const r=A.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:s}).where({id:i})));1!==r.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:r});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const s=e.ap(this.id);await(0,m.thenMap)(s.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await s.posterLink())}));const r=!0;this.imgAttrs.set(t,await s.imgAttrs(t,r,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(A.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new A.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,r=W,s=new WeakSet,n=function(){return r.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=r.dbl.first(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=r.dbl.first(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),E=i(65642),D=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),A=i(11944),O=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Q=i(30690),Y=i(13222),Z=i(50725),X=i(1724);class ee extends X.TimestampedModel{constructor(){super(...arguments),s.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Y.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,A.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Q.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Q.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const s=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",s).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,s,"m",r).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,q.assignAllFields)(this,(0,q.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,s,"m",r).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Q.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const s=await e.uriObject_();return null==s?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(s),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const s=e.ap(this.assetId),r=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>r.push(e))),this.isVideo)return r;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return r;const n=(0,A.compact)(await Promise.all([...await s.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return r.push(...(0,A.uniqBy)(n,(e=>e.size))),r}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,s=x.URI.parse(this.uri),r=await t.exists();if(null==e||(0,A.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:r};function n(){return(0,O.at)((0,O.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=s.scheme===G.PS_LIBRARY_SCHEME,l=o?s.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,O.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(s.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:r}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,s=new WeakSet,r=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const s=i(80294),r=i(75556);t.toAssetId=function(e){const t=(0,r.toGt0)(e?.assetId)??(0,r.toGt0)(e?.id);if(null==e||null==t||!(0,r.isNumber)(e?.capturedAtLocal))return;const i=((0,r.toGt0)(e.v)??(0,r.toGt0)(e.updateCount)??(0,r.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,r.gt0)(e.durationMs)&&(n.durationHMS=(0,s.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const s=i(87748),r=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,s.stringify)(e.priorValue),_newValueJson:(0,s.stringify)(e.newValue)}))))}get priorValue(){return(0,r.parseJSON)(this._priorValueJson)}get newValue(){return(0,r.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const s=i(7907);class r extends s.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=r,r.$tableName="AssetTag",r.$uniqueColumnName="assetId,tagId",r.$useCache=!1,r.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const s=i(4866),r=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,s.lazy)((()=>(0,r.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const s=i(4866),r=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,s.lazy)((()=>(0,r.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,s.lazy)((()=>(0,r.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var s;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const r=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[r.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const s=this[e];return null===s?[e,null]:!(0,f.isPrimitive)(s)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(s)]:[e,s]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:s}){const r=this.class(),n=(0,l.notEmptyOr)(s,r.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:r.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,s=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(s.$schema+"."+s.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const s=i(62936),r=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,r.libraryDataDirPosixFile)(e),(e=>(0,s.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const s=i(7162),r=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const s=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,r.includes)(s.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const s=new i;return null==t?s:d(s,t,(0,r.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,r){if(null!=t)return Array.isArray(t)?t.map(((t,s)=>e(t,i,`${r}[${s}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,s.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:r,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),E=i(1429),D=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),A=i(79563);t.ModelOps=class{constructor(e,t){s.add(this),this.model=e,this.db=t,r.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,r,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,A.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,s,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const s of e){const e=this.$cachedById(s);null!=e?t.push(e):i.push(s)}const s=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(s))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,r,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,s,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,s,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),s=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?s.push("DO NOTHING"):s.push("DO UPDATE SET",i),s.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const s=e[i];if(null==s)return;t[i]=s}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,s,"m",u).call(this,e),r=this.findOneBy(t);return h(this,s,"m",l).call(this,i,r),i!==e&&h(this,s,"m",l).call(this,e,i),i}h(this,r,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),r=[];for(const n of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,s,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,s]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(s,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),r.push(e)}}return r}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,s;do{i=this.allf((i=>(i=e.qb(i),null!=s&&(i=i.andWhere("id",">",s)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(s=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,s,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const r={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(r);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,s,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const s=i(4691),r=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,r.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void c().debug("applyOnce(): already done",{priorCompleted:r});const n=this.ops().insertOne(e),o=await t(n);return(0,s.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const s=i(70612),r=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),s=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(s),D.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:r.pid,hostname:(0,s.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const s=i(84253),r=i(1724);t.ProgressMetaNames=(0,s.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends r.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const s=i(4866),r=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,s.lazy)((()=>(0,r.mkLogger)("model.ShaBlocklist"))),f=(0,s.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,s.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,s.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),E=i(39784),D=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),A=i(14405),O=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:s.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of s.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return s.incrAssetCount(s.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||s.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return s.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=s.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});s.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?s.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?s.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return s.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new s;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,s,"m",r).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),s.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){s.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,r=s.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:r});try{if(null==r)s.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=r._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:r.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...r.path,e.name]),!1);s.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:r.id}))),this.delete()}}finally{t&&s.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return s.orderBy(s.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=s.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=s.ops().all(t);for(const e of i)s.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:s.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=s.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:s.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(A.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?s.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):s.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let s=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return s=s.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?s.orderByRaw(`ABS(Asset.id-${e.id})`):s.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,s,r]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(A.toAssetId))));for(const t of s)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(s)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(A.toAssetId));return this.logger().debug(this.path+": Found "+s.length+" related assets"),s}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,s=z,r=function(e){const t=new s;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new s;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=s.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>s.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{s._upsertDefaultRoots();const e=s.ops().all(s.orderBy(s.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],s.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const s=i(62936),r=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,r.tag_fts_root)(e._path),path:(0,r.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(s.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const r=c.$tableName;this.dbl.runScript([`INSERT INTO ${r}(${r}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const s=i(13779),r=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,s){this.tags=e,this.before=t,this.after=i,this.limit=s,this.logger=()=>(0,r.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,s.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,s.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,s.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],r=e.filter((e=>e.length>5));for(const e of r){const r=(0,s.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==r?i.push(e):r.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const s=i(70283),r=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,r.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,s.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,s.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},80796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeApplyDeleted=t.maybeApplyExcluded=void 0;const s=i(7162),r=i(99869),n=i(10408),a=i(17875),o=i(79141),l=i(11944),u=i(39938),c=i(87748),d=i(75556),h=i(2934),f=i(17078),m=i(42313),p=i(30690),g=i(89452),y=i(36310),v=i(65548),w=(0,s.mkLogger)("ops.ApplyExcluded");async function b(e,t){const i=v.Progress.insertNew(t?{uri:m.EmptyDeletedURI,state:"processing",volume:"๐Ÿ—‘๏ธ",scanningPct:0,hed:"Removing deleted assets from library and disk"}:{uri:m.EmptyRemovedURI,state:"processing",volume:"โ๏ธ",scanningPct:0,hed:"Removing excluded assets from library"}),{assetCount:s,assetFileCount:y}=(0,h.parseJSON)(e.value);(0,d.gt0)(s)&&(0,d.gt0)(y)||w.throw("Refusing to "+e.name+": invalid model counts",{op:e});const b=t?"deletedAt":"excludedAt",S=t=>t.where("Asset.shown",0).andWhere("Asset."+b,e.createdAt),P=p.Asset.dbl.pluckAllf((e=>S(e.select("Asset.id"))));if(P.length>s&&w.throw("Refusing to "+e.name+": too many assets!",{op:e,assetCount:P.length}),t){const t=g.AssetFile.dbl.pluckFirstf((e=>S(e.countDistinct("AssetFile.id").join("Asset","Asset.id","AssetFile.assetId"))));t>y&&w.throw("Refusing to "+e.name+": too many impacted files!",{op:e,dbAssetFileCount:t})}const M=[];function _(e){const i=P.length,s=[`Removed ${(0,f.plur)(i,"asset")} from your library.`+(e>=i?"":` ${(0,f.plur)(i-e,"asset")} need to be removed.`)];if(t){const e=(0,l.count)(M,(e=>e.unlinked));s.push((0,f.plur)(e,"file")+" deleted from disk."),(0,l.count)(M,(e=>!e.unlinked))>0&&s.push((0,f.plur)(e,"file")+" could not be deleted from disk. Check the logs for details.")}return s}const T=(0,r.rateLimited)({name:"applyRemovable",f:async e=>{e<0||(i.completePct=(0,d.clamp)(0,100,Math.round(e/P.length)),i.incompletePct=(0,d.clamp)(0,100,100-i.completePct),i.dek=_(e),i.upsert())},minCallDelayMs:500});w.info("applying...",{op:e,assetIds:P});try{for(const e of P){const i=await p.Asset.remove({assetId:e,blocklistShas:!0,unlinkAssetFiles:t});M.push(...i?.deletedMeta.filter((e=>(0,u.notBlank)(e.nativePath)))),await T(P.indexOf(e))}e.upsert({completedAt:Date.now()}),i.hed=t?"Emptied trash.":"Excluded assets removed.",i.dek=_(P.length),i.state="done",i.completedAt=Date.now(),i.upsert(),w.info("Complete!",{op:e})}catch(t){const s=(0,o.toWrappedError)("Could not apply "+(0,c.stringify)(e),{cause:t});(0,a.onError)(s),i.upsert({hed:"Failed: "+(0,n.errorToS)(s),state:"done",completedAt:Date.now()})}}t.maybeApplyExcluded=async function(){return y.Operation.applyIfPending({name:"applyExcluded"},(e=>b(e,!1)))},t.maybeApplyDeleted=async function(){return y.Operation.applyIfPending({name:"applyDeleted"},(e=>b(e,!0)))}},83148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPendingOperations=void 0;const s=i(80796);t.checkPendingOperations=async function(){await(0,s.maybeApplyExcluded)(),await(0,s.maybeApplyDeleted)()}},35735:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Queue=t.assetUpdatesQueueName2uri=t.assetUpdatesUri2QueueName=t.assetFileUpdatesQueueName2uri=t.assetFileUpdatesUri2QueueName=void 0;const s=i(46852),r=i(93813),n=i(91464),a=i(87130),o=i(96781);function l(e){return`assetFileUpdates:${r.AssetFileVersion}:${e}`}function u(e){return`assetUpdates:${r.AssetVersion}:${e}`}t.assetFileUpdatesUri2QueueName=l,t.assetFileUpdatesQueueName2uri=function(e){return(0,n.stripPrefix)(e,l(""))},t.assetUpdatesUri2QueueName=u,t.assetUpdatesQueueName2uri=function(e){return(0,n.stripPrefix)(e,u(""))};class c extends o.StatsModel{static itemCountForQueues(e){return(0,s.thenOrElse)(a.QueueItem.dbl.pluckFirstf((t=>t.countDistinct("QueueItem.id").join("Queue","Queue.id","QueueItem.queueId").whereIn("Queue.name",e))),(()=>0))}static truncate(){a.QueueItem.dbl.runf((e=>e.delete())),c.dbl.runf((e=>e.delete()))}items(){return a.QueueItem.ops().allf((e=>e.where({queueId:this.id})))}itemCount(){return a.QueueItem.dbl.pluckFirstf((e=>e.where({queueId:this.id}).count()))}upsertWorkItems(e){return a.QueueItem.ops().upsert(e.map((e=>({queueId:this.id,...e}))))}}t.Queue=c,c.$tableName="Queue",c.$uniqueColumnName="name"},87130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueueItem=void 0;const s=i(96781);class r extends s.StatsModel{eql(e){return null!=e&&(null!=this.id&&this.id===e.id||this.contents===e.contents&&this.queueId===e.queueId)}}t.QueueItem=r,r.$tableName="QueueItem",r.$uniqueColumnName="queueId,contents"},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const s=i(4866);t.statsDb=(0,s.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const s=i(19658),r=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,r.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:s.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},96781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatsModel=void 0;const s=i(7907),r=i(81520);class n extends s.Model{}t.StatsModel=n,n.$schema="stats",n.db=r.statsDb},16630:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const o=i(4866),l=i(7162),u=i(67654),c=i(46852),d=i(7383),h=i(39506),f=i(53525),m=i(98250),p=i(72461),g=i(31216),y=i(47874),v=i(43414),w=i(96593),b=i(11944),S=i(59694),P=i(39938),M=i(88491),_=i(66776),T=i(75556),E=i(30690),D=i(89452);t.isFileInSync=async function(e){return new x(m.PosixFile.for(e)).alreadySynced()};const k=new h.SerialLaterQueue;class x{constructor(e,t){this.file=e,s.set(this,void 0),r.set(this,new Set),this.alreadySynced=(0,d.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>a(this,s,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,d.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?a(this,s,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,o.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,o.lazy)((()=>v.Settings.useImageHashes.valueOrDefault?(0,p.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,o.lazy)((()=>(0,c.thenMap)(this.imageHash(),(e=>(0,b.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,o.lazy)((async()=>{const e=await this.capturedAt_();return a(this,s,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,d.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,P.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return a(this,s,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return a(this,s,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new E.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,d.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,g.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtOrImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,d.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return a(this,s,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;a(this,s,"f").debug("apply(): "+t+": returned null")}catch(e){throw a(this,s,"f").debug("apply(): "+t+" rejected: "+e),e}})),n(this,s,(0,l.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f"),this.ctx=(0,y.forceContextOrSetting)(t)}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),a(this,s,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}a(this,s,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(){const e=await this.file.uri_();if(null!=e)return D.AssetFile.ops().findOneBy({uri:e})??D.AssetFile.ops().findOneBy({uri:this.file.fileuri()});a(this,s,"f").warn("byUri() uri is null",{file:this.file})}assetByNormalizedPathUri(){return(0,c.thenMap)(this.file.normalizedPathUri_(),(e=>E.Asset.findFirstByFile((t=>t.where("AssetFile.uri",e)))))}assetBySha(){return(0,c.thenMap)(this.file.sha(),(e=>E.Asset.findFirstByFile((t=>t.where("AssetFile.sha",e)))))}async assetByCapturedAtOrImageHash(){const e=await this.capturedAt_();if(null==e)return a(this,s,"f").throw("Cannot import, capturedAt is null"+f.InternalErrorFlag);if(v.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=v.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,T.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},r=Math.max(M.secondMs,v.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,d.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:r});if(null==t)a(this,s,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:r});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(v.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void a(this,s,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const n=await this.dominantLabhashes();if((0,b.isNotEmpty)(n)){const t=e.localBoundaries({delta:4*r});if(null==t)a(this,s,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:r});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",n).orWhereIn("mode1",n).orWhereIn("mode2",n))));if(null!=e)return e}}return this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash))}))}async firstSimilarAssetByQuery(e,t){a(this,r,"f").size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(a(this,r,"f"))));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&a(this,s,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const n=(0,S.sortBy)(e.filter((e=>!a(this,r,"f").has(e.id))),(e=>[(0,_.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of n)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const n=(0,u.whyNotSameAsset)(t,e,i);if(null==n)return a(this,s,"f").info("Found sibling AssetFile",e),E.Asset.ops().findById(e.assetId);a(this,r,"f").add(e.id),a(this,s,"f").debug("Contemporary assetFile not similar: "+n,e?.uri)}}}t.AssetFileFinder=x,s=new WeakMap,r=new WeakMap},93898:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult=void 0;const u=i(4866),c=i(7162),d=i(78342),h=i(53525),f=i(87489),m=i(23872),p=i(24948),g=i(31216),y=i(47874),v=i(11944),w=i(39938),b=i(38625),S=i(39784),P=i(49374),M=i(93445),_=i(16630),T=i(50100);t.importFileToResult=async function(e,t){const i=P.Library.instanceRequired();return(0,p.syncReport)().wrap_({path:e.nativePath,from:"importFileToResult()",fn_:()=>new E(e,i.assetFileRepository(),t).apply_()})};class E{constructor(e,t,i){s.add(this),this.file=e,this.repo=t,this.start=Date.now(),r.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else{const t=await(0,m.whyRejectFile)(this.file,(0,M.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,r,"f").throwIfAborted();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i){l(this,r,"f").info("Deleting prior AssetFile, and requesting prior asset repair",{rejected:e,prior:i}),i.delete();const t={assetId:i.assetId,forceRebuildPreviews:(0,b.isTrue)(i.shown)};(0,f.submitTask_)("repairAsset",t)}if(l(this,r,"f").throwIfAborted(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,w.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,r,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,r,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,r,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,s,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,r,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new _.AssetFileFinder(e,i),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=E,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=async function(){l(this,r,"f").throwIfAborted();const e=await this.whyRejected();if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,r,"f").throwIfAborted();const t=await this.prior();if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,r,"f").throwIfAborted();const i=await this.assetFile_();if(null==i)return l(this,r,"f").throw("_apply(): unexpected null assetFile");const s=i.id;if(null==s)return l(this,r,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,r,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,r,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;l(this,r,"f").throwIfAborted();try{o=await(0,T.assetPostUpsertTasks_)(a,this.ctx)}catch(e){e instanceof d.AbortError?l(this,r,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,r,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:s,assetFile:i,asset:a,uri:n,uris:[n,...(0,S.toA)(o?.newAssetFileUris)]}}},97840:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){s.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,s,"m",r).call(this,e);return null!=t&&(await l(this,s,"m",n).call(this,e,t),await l(this,s,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),r=await e.posixFile_();null==r&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(r);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,s,"m",n).call(this,r,e),h=null!=await l(this,s,"m",o).call(this,r,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:r.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(r);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===r.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+r.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},s=new WeakSet,r=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const s=this.originalsDir.join(...i),r=await this.findLibraryFileWithSameContents(e,s);if(null!=r)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:r}),r;const n=await s.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:s}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),r=[];for(const e of i)r.push(await l(this,s,"m",a).call(this,e,t));return(0,S.compact)(r)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},50100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const s=i(7162),r=i(92356),n=i(78342),a=i(5685),o=i(79141),l=i(19371),u=i(46517),c=i(11944),d=i(43383),h=i(75556),f=i(49374),m=i(69258),p=i(30690),g=i(97840),y=i(55903),v=(0,d.defer)((()=>(0,s.mkLogger)("sync-file.AssetPostUpsertTasks"))),w=(0,d.defer)((()=>new a.LastOneInWins("Asset tasks")));function b(e,t){const i=v().addContext(`.postUpsertAssetTasks_(Asset:${e?.id})`);if(t.skipPreviews&&t.skipAssetTagging)return void i.info("skipped (skipPreviews && skipAssetTagging)");if(null==e)return i.throw("unexpected null asset",{asset:e});const s=e.id;return null==s?i.throw("unexpected null asset.id",{asset:e}):w().enqueue(s,(async s=>{try{return async function(e,t,i,s){const n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted(s),(0,c.isEmpty)(a)&&(await p.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,g.mayCopyAssetsToLibrary)()){const t=f.Library.instanceRequired().assetFileRepository();for(const r of a){e.throwIfAborted(s);try{if(await r.exists()){const e=await t.maybeCopyToLibrary_(r,i);null!=e&&o.newAssetFileUris.push(e.uri)}}catch(t){e.warn("Failed to copy variation to library, but we'll try to continue",{af:r,error:t})}}}const d=i.skipPreviews?void 0:await(0,y.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...i,ac:s}),w=await async function(e,t){if((0,h.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?v().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,r.bestExistingAssetFile)(e.getAssetFiles())}(t,d);if(null==w)return e.throw("null primaryOrShownAssetFile_()",{asset:t});if(t.markShownAndUpsert_(w),i.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,m.tagAndUpsertAsset_)(t),!0!==i.skipPreviews&&t.isVideo()){const s=await(t.getShown()?.posixFile_());if(null==s)return e.throw("null asset.getShown().posixFile",{asset:t});o.transcoded=null!=await(0,u.transcode_)(s,l.Previews.instance().ap(n).mp4(),{force:i.forceRebuildPreviews})}return o}(i,e,t,s.signal)}catch(t){if(t instanceof n.AbortError)return void i.warn("aborted, next caller will clean up my mess",{error:t});const s=[t];i.error("failed, marking asset unshown",{error:t});try{e.markUnshownAndUpsert()}catch(e){i.error("failed to mark asset unshown",{upsertError:e}),s.push(e)}throw new o.WrappedError("Failed to post-process assset "+e.id,{causes:s})}}))}t.assetPostUpsertTasks=function(e,t){try{return b(e,t)}catch(e){if(e instanceof n.AbortError)return void v().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=b},91877:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuccessResult=t.isErrorResult=t.isImportResult=void 0;const s=i(24948),r=i(39938),n=i(75556);function a(e){return null!=e&&(0,r.notBlank)(e.path)&&s.SyncFileStates.has(e.state)}function o(e){return(0,r.notBlank)(e.error)||e.state===s.SyncFileStates.failed}t.isImportResult=a,t.isErrorResult=o,t.isSuccessResult=function(e){return null!=e&&!o(e)&&(0,n.gt0)(e.assetId)&&(0,n.gt0)(e.assetFileId)&&a(e)}},5848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset=void 0;const s=i(13779),r=i(7162),n=i(93813),a=i(46080),o=i(67654),l=i(92356),u=i(46852),c=i(6667),d=i(47874),h=i(43414),f=i(11944),m=i(39938),p=i(38625),g=i(24603),y=i(30690),v=i(89452),w=i(50100),b=i(84249);async function S(e){const[t,i]=(0,s.partition)(e,(e=>e.isVersionUpToDate()));for(const e of i){const i=t.find((t=>t.sha===e.sha));if(null!=i){(0,r.mkLogger)("UpdateAsset("+e.assetId+")").info("backfilling",{sibling:i,dest:e});const t=await e.updateFromShaSibling_(i);null!=t&&t.upsert()}}}t.updateAsset=async function(e){try{const t=await async function(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,s=(0,r.mkLogger)(`sync-file.UpdateAsset(${i})`),P=y.Asset.ops().findById(i);if(null==P)return s.throw("no such asset");const M=P.$clone(),_=P.getShown()?.$clone();(await(0,u.mapAsync)({name:"UpdateAsset.updateAssetFile",arr:P.getAssetFiles(),f:e=>(0,b._updateAssetFile_)({ctx:t,assetFileId:e.id,af:e})})).some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&P.clear(),await S(P.getAssetFiles());const T=(0,l.sortAssetFiles)(P.getAssetFiles()),E=T?.[0];if(null==T||null==E)return s.warn("No existing files. Skipping for now."),P.markUnshownAndUpsert(),{asset:P,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!E.isVersionUpToDate())return s.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:E}),P.markUnshownAndUpsert(),{asset:P,rejected:`Best AssetFile:${E.id}, could not be updated. Un-showing Asset:${i}`};const D=await E.capturedAt();if(null==D)return s.warn("Best file failed to extract a captured-at",{bestAcceptedAF:E}),P.markUnshownAndUpsert(),{asset:P,rejected:`Best AssetFile:${E.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const k=new Set,[x,C]=await(0,u.partitionAsync)(T,(e=>(0,o.isSimilarAssetFile)(e,E)));if((0,f.isNotEmpty)(C)){const e=await(0,a.aggregateAssetFiles)(C);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});k.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),s.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function F(e){return(0,f.uniq)(x.map((t=>t[e])))}const I=await Promise.all(x.map((e=>e.capturedAt()))),A=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,O=I.map((e=>e?.localBoundaries({delta:A}))),L=(0,c.min)(O.map((e=>e?.start)))??D.localBoundaries({delta:A})?.start,R=(0,c.max)(O.map((e=>e?.end)))??D.localBoundaries({delta:A})?.end,N=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${E.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",F("sha")),null==L||null==R?s.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:L,endBoundary:R}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[L,R]),e.orWhereIn("AssetFile.meanHash",F("meanHash")).orWhereIn("AssetFile.diffHash",F("diffHash")).orWhereIn("AssetFile.dctHash",F("dctHash"))))));s.info("asset file candidates for adoption: ",N.map((e=>e.posixPathFromGrandparent)));const B=[];for(const e of N)try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,E)&&(s.info("adopting similar asset file",{af:e}),k.add(e.assetId),e.shown=!1,P.addAssetFile(e),e.upsert(),B.push(e))}catch(t){s.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}s.info("fetched expansion",{retainAFs:x.map((e=>e.id)),rejectAFs:C.map((e=>e.id)),externalAssetFiles:N.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:B.map((e=>e.posixPathFromGrandparent))}),await S([...x,...B]),t.skipPreviews&&t.skipAssetTagging?(s.info("skipping previews and tagging",t),P.upsert()):await(0,w.assetPostUpsertTasks_)(P,t);const j=!(0,g.eql)(M,P),z=!(0,g.eql)(_,P.getShown()),V=!(j||z||t.forceRebuildPreviews||t.forceSync);return s.tap({msg:"updateAsset() result",level:"info",result:{asset:P,assetIdsToUpdate:Array.from(k),assetFiles:P.assetFiles,skipped:V},meta:{ctx:t,assetChanged:j,primaryAssetFileChanged:z}})}(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}}},84249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t._updateAssetFile_=t.updateAssetFile=void 0;const s=i(92356),r=i(10408),n=i(7162),a=i(47874),o=i(25116),l=i(11944),u=i(39938),c=i(61570),d=i(30690),h=i(89452);async function f({ctx:e,assetFileId:t,af:i}){const s=(0,n.mkLogger)(`updateAssetFile(${t})`),r=await(i?.posixFile_()),a={id:t,assetFileId:t,path:r?.nativePath,uri:i?.uri};if(null==i)return{...a,error:"db record not found"};if(null==r)return{...a,error:"file for URI not found"};const l=await(r?.isDeletedUri(i.uri));if(null==l)return s.info("no-op: file URI points to an unmounted volume",a),{...a,skipped:!0};const c=await i.whyRejected();if(l||!(0,u.blank)(c)){const e={...a,rejected:c,deleted:l};return s.warn("file was deleted or rejected. Deleting.",e),i.delete(),e}const d=await r.uri_();if(!await(0,o.uriIsEquivalent)(d,i.uri)){const t=await m(i,d,e.forceSync);if(null!=t)return{...a,...t}}return!e.forceSync&&await i.matchesFile()?(s.info("no-op: file already matches db record",a),i.touch(),{...a,skipped:!0}):{...a,...await p(i,e.forceSync)}}async function m(e,t,i){const r=(0,n.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,l.uniq)([...(0,o.uriEncodingVariants)(e.uri),...(0,o.uriEncodingVariants)(t)]);r.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const u=h.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,l.isNotEmpty)(u)){r.warn("Found other AssetFiles with equivalent URIs.",{afIds:u.map((e=>e.id))});const t=[e,...u],n=(0,s.sortAssetFiles)(t);if((0,l.isEmpty)(n))return r.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,c.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const o=t.map((e=>e.id));for(const e of n)if(await e.exists()){h.AssetFile.dbl.runf((t=>t.whereIn("id",o.filter((t=>t!==e.id))).delete()));const s=p(e,i);return d.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,l.uniq)(t.map((e=>e.assetId)))))),s}}r.info("no-op, no duplicate URIs.")}async function p(e,t){return null!=await e.upsertIfNeeded_(void 0,t)&&d.Asset.touch([e.assetId]),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await f({ctx:(0,a.forceContextOrSetting)(e),assetFileId:e.assetFileId,af:h.AssetFile.ops().findById(e.assetFileId)})}catch(t){return{id:e.assetFileId,...e,error:(0,r.errorToS)(t)}}},t._updateAssetFile_=f,t.handleAssetFileUriChange=m,t.updateAssetFileIfNeeded=p},55903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const s=i(53525),r=i(19371),n=i(7162),a=i(47874),o=i(25116),l=i(11944),u=i(43383),c=i(24603),d=i(75556),h=i(61570),f=i(39784),m=i(30690),p=(0,u.defer)((()=>(0,n.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,f.toA)(e.assetFiles).find((e=>(0,d.gt0)(e.assetId)))?.assetId,i=(0,a.forceContextOrSetting)(e),n=p().addContext(".Asset:"+t);if(i.skipPreviews)return void n.warn("skipPreviews is true: no-op");if(!(0,d.gt0)(t))return n.throw("invalid assetId",{assetId:t});const u=e.asset??m.Asset.ops().findById(t);if(null==u)return n.throw("Asset:"+t+" not found");n.throwIfAborted(e.ac);try{const a=await u.getExistingAssetFiles();if((0,l.isEmpty)(a))return void n.warn("no existing assetFiles",{asset:u});const d=r.Previews.instance().ap(t),f=await d.readInfo();n.throwIfAborted(e.ac);const m=await(0,r.buildAssetPreviews_)({...i,assetId:t,assetFiles:a}),p=a.find((e=>e.id===m?.assetFileId))??a.find((e=>(0,o.uriIsEquivalent)(m?.uri,e.uri)));n.info("buildAssetPreviews_()",{result:m,primaryAssetFile:p});const g=await(p?.posixFile_());if(null==p||null==g||!0!==await(g?.exists()))return n.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:m,assetFiles:a.map((e=>(0,h.pick)(e,"id","uri"))),primaryAssetFile:p,primaryPosixFile:g});const y=(0,c.eql)(f,m),v=null==m||y;return{...m,noop:v}}catch(e){throw n.warn("Failed to update previews. Un-showing asset "+t,{error:e}),u.markUnshownAndUpsert(),e}}},12474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateSuccessResult=t.isUpdateErrorResult=void 0;const s=i(39938),r=i(75556);t.isUpdateErrorResult=function(e){return null!=e&&(0,s.notBlank)(e.error)},t.isUpdateSuccessResult=function(e){return null!=e&&(0,r.gt0)(e.id)&&(0,s.blank)(e.error)}},24940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleUpdateCommand=t.describeUpdateCommand=t.UpdateTask=t.validUpdateCommandOrElse=void 0;const s=i(5712),r=i(79378),n=i(4866),a=i(7162),o=i(7383),l=i(49379),u=i(43414),c=i(11944),d=i(87748),h=i(75556),f=i(82798),m=i(91877),p=i(5848),g=i(84249),y=i(12474),v=(0,n.lazy)((()=>(0,a.mkLogger)("sync-file.UpdateTask")));function w(e){return(0,h.gt0)(e.assetId??e.assetFileId)||v().throw("validUpdateCommand(): missing asset or assetFile id",{fatal:!1,retriable:!1,cmd:e}),e}t.validUpdateCommandOrElse=w;class b extends s.Task{constructor(e){super((0,d.stringify)(w(e)),(e=>this.parse(e))),this.cmd=e,this.name=`UpdateTask(${(0,d.stringify)(e)})`}toString(){return this.name}parse(e){for(const t of(0,c.compactBlanks)((0,f.toS)(e).split("\n")).reverse()){const e=(0,r.parseJSON)(t);if((0,y.isUpdateSuccessResult)(e))return e}return v().throw(this.name+".parse() failed",{input:e})}}function S(e){const t=e;return(0,h.gt0)(t.assetId)?"updateAsset:"+t.assetId:(0,h.gt0)(t.assetFileId)?"updateAssetFile:"+t.assetFileId:(0,h.gt0)(t.assetPreviewId)?"updateAssetPreviews:"+t.assetPreviewId:"invalid command: "+(0,d.stringify)(e)}t.UpdateTask=b,t.describeUpdateCommand=S,t.handleUpdateCommand=function e(t){v().info("handleUpdateCommand()",{cmd:t});const i=t,s=(0,o.time)("sync-file."+S(t),(0,h.gt0)(i.assetId)?(0,p.updateAsset)(i):(0,h.gt0)(i.assetFileId)?(0,g.updateAssetFile)(i):v().throw("Invalid update command "+(0,d.stringify)(t)));if((0,m.isErrorResult)(s)){const i=u.Settings.maxRetries.valueOrDefault,r=(0,l.isNonRetriableError)(s.error);if((0,h.gt0)(i)&&(0,h.gt0)(t.retries)&&!0!==r)return v().warn("Retrying failed command",{cmd:t,result:s}),e({...t,retries:(t.retries??u.Settings.maxRetries.valueOrDefault)-1});v().warn("Command failed, and cannot retry",{result:s,isNonRetriable:r,retries:t.retries,maxRetries:i})}return s}},54620:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const s=i(37980),r=i(64063),n=i(9972),a=i(37445),o=i(51053),l=i(43414),u=i(7127),c=i(26367),d=i(78877),h=i(80338),f=i(92045),m=i(50763),p=i(51315),g=i(64239),y=i(90339);!async function(){if(o.isElectron)new y.SyncService;else{const e=await new s.CLI(u.ServiceNames.sync,"[files-or-directories...]","If paths are provided on the command line, they should be fully-qualified.\n\n* Paths to directories will be scanned recursively.\n* Paths to files will be imported if they pass configured filters.\n\nNote that sync will spawn 1 or more `worker` processes to work in parallel.").add(p.RebuildArg,h.ForceArg,n.TimingArg,c.DropWorkQueuesArg,m.NoFilterArg,g.SkipUpdateArg,d.ExitWhenDoneArg,a.WriteSettingsArg,f.LogArgs,r.ColorArgs).parse();l.Settings.argvScanPaths.envValue=e.args,new y.SyncService}}()},28688:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileQueue=void 0;const s=i(13779),r=i(70259),n=i(7383),a=i(87489),o=i(98462),l=i(95725),u=i(24948),c=i(69060),d=i(7162),h=i(6667),f=i(43414),m=i(63526),p=i(35280),g=i(11944),y=i(39938),v=i(38625),w=i(82798),b=i(49049),S=i(89452),P=i(87130),M=i(9497),_=i(38791);class T{static async for(e,t){return new T((0,l.toNativePath_)(e),t)}constructor(e,t){this.logger=(0,d.mkLogger)("AssetFileQueue"),this.fileListener=async e=>{const t=e.map((e=>(0,l.isSimpleFile)(e)?e:o.BaseFile.for(e)));if(this.logger.debug("fileListener()",t),f.Settings.forceSync.valueOrDefault)return this.enqueueSimpleFiles(t);{const e=!0,{fresh:i,stale:s}=await(0,n.time)("sync.precheckFiles",(()=>(0,_.precheckFiles)(t,e)));return this.logger.debug("fileListener()",{fresh:i,stale:s}),this.enqueueSimpleFiles(s)}},this.imgQueue=M.WorkQueue.mk({queueNames:["img:"+e],processItem:e=>t(e.contents)}),this.vidQueue=M.WorkQueue.mk({queueNames:["vid:"+e],processItem:e=>t(e.contents),concurrent:!1})}async waitForCompletion(){await Promise.all([this.imgQueue.awaitDrain(),this.vidQueue.awaitDrain()])}clearRecentlyProcessed(){this.imgQueue.recentlyProcessed.clear(),this.vidQueue.recentlyProcessed.clear()}get currentPaths(){return[...this.imgQueue.currentQueueContents(),...this.vidQueue.currentQueueContents()]}get currentBaseFiles(){return this.currentPaths.map((e=>o.BaseFile.for(e)))}hasPath(e){for(const t of this.currentPaths)if(e===t)return!0;return!1}get currentVideoJobCount(){return this.vidQueue.currentWorkCount()}get processedCount(){return this.processedImageCount+this.processedVideoCount}get processedImageCount(){return this.imgQueue.processedCount()}get processedVideoCount(){return this.vidQueue.processedCount()}get avgImageProcessingTime(){return this.imgQueue.processMs.p84}get avgVideoProcessingTime(){return this.vidQueue.processMs.p84}async stats(){return{pendingCount:await this.pendingCount(),processedImageCount:this.processedImageCount,processedVideoCount:this.processedVideoCount,avgImageProcessingTime:this.avgImageProcessingTime,avgVideoProcessingTime:this.avgVideoProcessingTime}}currentCounterState(){return{processedImageCount:this.processedImageCount,processedVideoCount:this.processedVideoCount}}itemQuery(e){return P.QueueItem.query().whereIn("queueId",e)}async queueIds(){return[...this.imgQueue.queueIds(),...this.vidQueue.queueIds()]}async pendingCount(){return P.QueueItem.dbl.pluckFirst(this.itemQuery(await this.queueIds()).count("id"))}async pendingContent(e=10){const t=await this.queueIds();return P.QueueItem.dbl.pluckAll(this.itemQuery(t).select("contents").limit(e))}pendingImagesCount(){return this.imgQueue.pendingWorkCount()}pendingVideoCount(){return this.vidQueue.pendingWorkCount()}async etaMs(){return(0,h.sum)([this.imgQueue.etaMs(),this.vidQueue.etaMs()])}recentFileProgress(){return(0,g.compact)([this.imgQueue.recentlyProcessed.last()?.contents,this.vidQueue.recentlyProcessed.last()?.contents])}async enqueueWork(e){if((0,g.isEmpty)(e))return;const[t,i]=(0,s.partition)(e.filter(m.isAssetFileExt),m.isVideoExt);this.logger.info("enqueueWork()",{input:e.map(w.toS),videos:t.map(w.toS),images:i.map(w.toS)}),this.imgQueue.enqueueWork(i.map((e=>({contents:(0,l.toNativePath_)(e)})))),this.vidQueue.enqueueWork(t.map((e=>({contents:(0,l.toNativePath_)(e)}))))}async enqueueOrTouchAssetFiles(e){const t=[],i=f.Settings.copyAssetsToLibrary.valueOrDefault&&!await(0,c.l)(),s=[];await(0,r.withBoundedConcurrency)({name:"enqueueOrTouchAssetFiles",laters:e.map((e=>async()=>{const r=await e.posixFile_(),n={path:r?.nativePath??e.uri,url:(0,p.mkAssetUrl)(e.assetId)?.toString()};if(!0===await e.isFileDeleted()){e.delete();const t={assetId:e.assetId,forceRebuildPreviews:(0,v.isTrue)(e.shown)};(0,a.submitTask_)("repairAsset",t),(0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",details:"file no longer exists",state:u.SyncFileStates.deleted})}if(null==r)return void this.logger.warn("Failed to decode URI to existing file",{af:e});const o=await e.whyNotMatchesFile(),l=i&&(0,v.isTrue)(e.shown)&&!e.uri.startsWith(b.PS_LIBRARY_SCHEME);(0,y.notBlank)(o)||l?((0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",state:u.SyncFileStates.enqueued,details:(0,g.compactBlanks)([o,l?"PS_COPY_ASSETS_TO_LIBRARY is true and this primary variant isn't in the library":""]).join("; ")}),s.push(r)):((0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",details:"Library db is already in sync for this file",state:u.SyncFileStates.noop}),t.push(e.id))}))}),S.AssetFile.touch(t),await this.enqueueWork(s),this.logger.info("enqueueOrTouchAssetFiles()",{freshAssetFileIds:t,staleFiles:s})}async enqueueSimpleFiles(e){if((0,g.isNotEmpty)(e)){for(const t of e)(0,u.syncReport)().onProgress({path:(0,l.toNativePath_)(t),from:"AssetFileQueue",state:u.SyncFileStates.enqueued});await this.enqueueWork(e)}}}t.AssetFileQueue=T},58297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetPostUpsertQueue=t.AssetPostUpsertQueueName=void 0;const s=i(79378),r=i(4866),n=i(7162),a=i(47874),o=i(75556),l=i(9497),u=i(30690),c=i(50100);t.AssetPostUpsertQueueName="AssetPostUpsertTasks";const d=(0,r.lazy)((()=>(0,n.mkLogger)("sync.AssetPostUpsertQueue")));t.mkAssetPostUpsertQueue=function(){return l.WorkQueue.mk({queueNames:[t.AssetPostUpsertQueueName],concurrent:!0,async processItem(e){const t=(0,s.parseJSON)(e.contents),i=(0,o.toGt0)(t?.assetId)??(0,o.toGt0)(e.contents);if(null==i)return void d().error("invalid assetId",{qi:e});const r=u.Asset.ops().findById(i);if(null!=r)return(0,c.assetPostUpsertTasks_)(r,(0,a.forceContextOrSetting)({skipAssetTagging:!1,skipPreviews:!1}));d().error("asset not found",{assetId:i})}})}},43600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUpdateQueue=void 0;const s=i(79378),r=i(43414),n=i(11944),a=i(75556),o=i(9497),l=i(52257);t.mkAssetUpdateQueue=async function(e){if(r.Settings.noAssetUpdates.valueOrDefault)return;const t=(0,n.compactBlanks)(await(0,l.enqueueAssetUpdates)());return(0,n.isEmpty)(t)?void 0:o.WorkQueue.mk({queueNames:t,concurrent:!1,processItem(t){const i=(0,s.parseJSON)(t.contents);return e(i?.assetId??(0,a.toInt)(t.contents))},endWhenDone:!0})}},73571:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectorySync=void 0;const a=i(24945),o=i(4866),l=i(7162),u=i(19658),c=i(70283),d=i(91464),h=i(47284),f=i(36079),m=i(91641),p=i(4691),g=i(20681),y=i(97463),v=i(3955),w=i(24948),b=i(59220),S=i(31359),P=i(6667),M=i(43414),_=i(67220),T=i(59387),E=i(11944),D=i(39938),k=i(38625),x=i(88491),C=i(6314),F=i(66776),I=i(75556),A=i(17078),O=i(89452),L=i(65548),R=i(33075),N=i(28688);class B extends h.DoneWrapper{static async for({root:e,rootUri:t,fileProcessor:i}){if(await e.clear().isDirectory())return new B(e,t,await N.AssetFileQueue.for(e,i));(0,l.mkLogger)("sync.DirectorySync").warn("Cannot sync "+e+": it's not a directory (or not readable)",{root:e,rootUri:t})}constructor(e,t,i){super("sync.DirectorySync("+e+")",(()=>this.onEnd()),m.EndableRanks.first),s.add(this),this.root=e,this.rootUri=t,this.afq=i,this.start=Date.now(),this._isScanning=!0,this.eta=new S.ETA,this.recentlyScannedDirs=new a.BoundedList(10),this.scannedDirsCount=0,this.preDone=new C.Latch,this.priorProcessedImageCount=0,this.priorProcessedVideoCount=0,this._progress=(0,o.lazy)((()=>L.Progress.insertNew({uri:this.rootUri,volume:this.root.nativePath}))),this.forceDirectoryScan=(0,o.lazy)((()=>{const e=M.Settings.forceSync.valueOrDefault,t=M.Settings.argvScanPaths.values.some((e=>this.root.eql(e)));return this.logger.tap({msg:"forceDirectoryScan",result:e||t,meta:{forceSync:e,isArgvPath:t}})})),this.initialMeta=(0,o.lazy)((async()=>this.forceDirectoryScan()?void 0:this._progress().getMetaAsRecord())),this.saveSyncProgress=(0,o.lazy)((()=>L.Progress.saveSyncState(this)),u.isTest?100:x.secondMs),this.saveLastScannedDirectory=(0,o.lazy)((async()=>{const e=this._progress();e.setMeta(R.ProgressMetaNames.scannedDirectoryCount,this.scannedDirsCount.toString());const t=this.recentlyScannedDirs.at(-1);null!=t&&e.setMeta(R.ProgressMetaNames.lastScannedDirectory,t)}),u.isTest?100:x.secondMs),this.directoryListener=e=>(0,D.mapNotBlank)(e?.nativePath,(t=>(this.scannedDirsCount++,this.recentlyScannedDirs.push(t),this.logger.debug("directoryListener()",{scannedDirsCount:this.scannedDirsCount,dir:e.nativePath}),this.saveLastScannedDirectory()))),this.earliestStartTime=(0,o.lazy)((async()=>{const e=(await L.Progress.times()).find((e=>e.uri===this.rootUri));return e?.lastStartedAt??Date.now()})),this.retryEnqueued=(0,o.lazy)((async()=>{const e=await(0,w.recentSyncReports)();if((0,E.isEmpty)(e))return void this.logger.warn("retryEnqueued(): no-op: no recent sync reports");const t=await(0,b.unprocessedPaths_)({syncReportJsons:e,acceptPath:e=>(0,v.containedByNativePath)({ancestor:this.root,descendant:e})});this.logger.info("retryEnqueued(): parsed prior sync reports to find stuck paths.",{stuck_length:t.length,stuck:t}),await this.afq.enqueueWork(t)})),this.run=(0,o.lazy)((async()=>{const e=await this.initialMeta();if(this.logger.info("setup()",{meta:e}),(0,F.map)(e?.lastScannedDirectory,(e=>this.recentlyScannedDirs.push(e))),(0,c.mapGt0)(e?.processedImageCount,(e=>this.priorProcessedImageCount=e)),(0,c.mapGt0)(e?.processedVideoCount,(e=>this.priorProcessedVideoCount=e)),await n(this,s,"m",r).call(this),this.logger.info("setup() setting isScanning to false."),this._isScanning=!1,await this.afq.waitForCompletion(),M.Settings.retryEnqueued.valueOrDefault&&(this.afq.clearRecentlyProcessed(),await this.retryEnqueued(),await this.afq.waitForCompletion()),await this.maybeEnqueueStaleAssetFiles(),await this.afq.waitForCompletion(),!this.ended){this.logger.info("DONE! Marking Progress as complete and updating meta."),await this.preDone.resolve();const e=await this.progress.refresh();e.setMeta("completedDirectorySync","true"),e.upsert({completedAt:Date.now()}),await this.end()}})),this.progress=(0,g.lazyAsync)({desc:this.name+".progress",timeoutMs:x.secondMs,ttlMs:250,later:async()=>{const e=this.isDone()||this.preDone.isResolved(),t=(0,_.isPaused)()||(0,p.ending)(),i=e?"done":t?"paused":"processing",s=[];e||t||((0,D.mapNotBlank)(this.afq.recentFileProgress(),(e=>s.push(e))),this.isScanning&&s.push("Scanning "+(0,D.firstNotBlank)(this.recentlyScannedDirs.shiftOrFirst(),this.root.nativePath)));const r=[];let n="Processed "+(0,A.plur)(this.processedImageCount,"photo")+" and "+(0,A.plur)(this.processedVideoCount,"video")+".";this.processedImageCount+this.processedVideoCount>0&&r.push(n);const a=await this.pendingCount();!e&&a>0&&(r.push(this.isScanning?"At least":"",(0,A.fmt)(a),"remain to be processed"),n+=` ${this.isScanning?"At least":""} ${(0,A.fmt)(a)} to do.`),a<10&&s.push((await this.afq.pendingContent()).join(", ")),s.push((0,E.compactBlanks)(r).join(" ")),a<10&&s.push();const o=[];o.push((0,d.capitalize)(i)),e||(0,F.map)(this.eta.fmtEstimate(),(e=>o.push(e)));const l=this._progress();this.processedImageCount>1&&l.setMeta(R.ProgressMetaNames.processedImageCount,String(this.processedImageCount)),this.processedVideoCount>1&&l.setMeta(R.ProgressMetaNames.processedVideoCount,String(this.processedVideoCount));const u=await this.percents(),c={state:i,hed:o.join(", "),dek:s,updatedAt:Date.now(),...u};return"done"===i&&(c.completedAt=Date.now()),this.logger.tap({msg:".progress()",level:"info",result:l.assignFromPojo(c)})}}),this.doneLatch.observe(this.run())}async onEnd(){await(0,f.end)(this.directoryWalker),await this.saveSyncProgress.refresh(),await(w.syncReport.prior()?.close())}async maybeEnqueueStaleAssetFiles(){if(!M.Settings.forceSync.valueOrDefault&&(0,k.isTrue)((await this.initialMeta())?.enqueuedStaleFiles))this.logger.info("maybeEnqueueStaleAssetFiles() no-op: prior enqueuedStaleFiles.");else{const e=this._progress(),t=await this.earliestStartTime();this.logger.info("maybeEnqueueStaleAssetFiles() starting enqueue",{assetFileQueuePendingCount:await this.afq.pendingCount()}),await O.AssetFile.ops().batched({onResults:async e=>this.afq.enqueueOrTouchAssetFiles(e),qb:e=>e.whereLike("uri",this.rootUri+"%").andWhere("updatedAt","<",t)}),this.logger.info("maybeEnqueueStaleAssetFiles() finished enqueue",{assetFileQueuePendingCount:await this.afq.pendingCount()}),e.setMeta(R.ProgressMetaNames.enqueuedStaleFiles,"true")}}get processedImageCount(){return this.priorProcessedImageCount+this.afq.processedImageCount}get processedVideoCount(){return this.priorProcessedVideoCount+this.afq.processedVideoCount}processedCount(){return this.processedImageCount+this.processedVideoCount}pendingCount(){return this.afq.pendingCount()}get isScanning(){return this._isScanning}async estimatedScannedPct(){if(!this.isScanning)return 100;const e=100/-(this.scannedDirsCount/500+1)+100;return(0,I.sigFigs)(e,4)}async percents(){if(this.isDone())return{completePct:100,incompletePct:0,scanningPct:0};const e=(0,I.round)(await this.estimatedScannedPct()),t=100-e,i=this.processedCount(),s=await this.pendingCount(),r=0===s&&0===i?0:(0,I.round)(e*(i/(s+i))),n=100-(r+t),a={completePct:r,incompletePct:n,scanningPct:t};if(this.logger.debug("percents(): ",{scannedPct:e,processed:i,pending:s,p:a}),100!==(0,P.sum)([a.completePct,a.incompletePct,a.scanningPct])&&this.logger.warn("percents(): BUGGED",{p:a,processed:i,pending:s,scannedPct:e,scanningPct:t,incompletePct:n,completePct:r}),100===e&&i>7){const e=this.afq,t=(0,T.maxConcurrentImports)(),i=e.pendingImagesCount(),s=e.pendingVideoCount(),r=0===i?void 0:(0,F.map)(e.avgImageProcessingTime,(e=>(0,I.sigFigs)(i*e/t,2))),n=0===s?void 0:(0,F.map)(e.avgVideoProcessingTime,(e=>(0,I.sigFigs)(s*e,2))),a=(0,P.sum)([r,n]);a>0&&(this.logger.info("ETA",{eta:a,imgMs:r,vidMs:n,imgCount:i,imgConcurrency:t,vidCount:s}),this.eta.push(a))}return a}}t.DirectorySync=B,s=new WeakSet,r=async function(){const e=this.forceDirectoryScan(),t=await this.initialMeta();if(!e&&(0,k.isTrue)(t?.completedDirectoryScan))return this.logger.tap({msg:"#maybeRunDirectorySync_(): no-op",result:void 0,meta:{forceDirectoryScan:e,initialMeta:t}});const i=this._progress();this.scannedDirsCount=(0,I.toInt)(t?.scannedDirectoryCount)??0,this.directoryWalker=new y.DirectoryWalker(await this.root.directoryEntry(),this.afq.fileListener,this.directoryListener,t?.lastScannedDirectory),await this.directoryWalker.awaitEnd(),this.logger.info("maybeRunDirectorySync_() completed directoryWalker",{scannedDirsCount:this.scannedDirsCount}),i.setMeta(R.ProgressMetaNames.completedDirectoryScan,"true")}},27864:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryTaggerOperation=void 0;const s=i(4866),r=i(91641),n=i(95557),a=i(4691),o=i(46852),l=i(31359),u=i(6667),c=i(11944),d=i(39938),h=i(6314),f=i(89253),m=i(75556),p=i(17078),g=i(42313),y=i(11254),v=i(96672),w=i(30690),b=i(89452),S=i(36310),P=i(65548);class M extends n.EndableWrapper{constructor(e){super("TagAssetsWithFiles",(()=>null),r.EndableRanks.first),this.priorProgress=e,this.start=Date.now(),this._eta=new l.ETA,this._done=new h.Latch,this._progress=(0,s.lazy)((()=>(0,o.thenOrElse)(this.priorProgress,(()=>P.Progress.insertNew({uri:g.RebuildingURI,volume:"๐Ÿ”„"}))))),this._done.observeQuietly(S.Operation.applyOnce({name:"applyNewTagger",value:y.TagRoots.fs,version:1},(()=>this._run())))}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){if(this.isDone())return(await this._progress()).assignFromPojo({state:"done",hed:"Finished rebuilding your library ๐ŸŽ‰",dek:[],completePct:100,incompletePct:0,scanningPct:0});if(null==this.eta()||null==this.doneCount||null==this.todoCount)return;const e=await this._progress(),t=this.doneCount/(this.todoCount+this.doneCount),i=(0,m.clamp)(0,100,Math.round(100*t)),s=this._eta.fmtEstimate(),r=`Adding ${y.TagRoots.fs} tags to your library`+(0,d.mapNotBlankOr)(s,(e=>", "+e),"โ€ฆ");return e.assignFromPojo({state:"processing",hed:r,dek:[`Tagged ${(0,p.fmt)(this.doneCount)} URIs, ${(0,p.fmt)(this.todoCount)} remain.`],completePct:i,incompletePct:100-i,scanningPct:0})}eta(){if(null==this.todoCount||null==this.doneCount||0===this.todoCount)return;const e=(Date.now()-this.start)/this.doneCount*this.todoCount;return this._eta.push(e),this._eta.avg()}async _run(){return this.todoCount=b.AssetFile.dbl.pluckFirstf((e=>_(e.countDistinct("AssetFile.id")))),this.doneCount=0,b.AssetFile.dbl.batched({onResults:e=>{for(const t of(0,f.groupBy)(e,(e=>e.assetId)).values()){if((0,a.ending)())return;const e=t[0].assetId,i=w.Asset.ops().findById(e);null==i?this.logger.warn("Asset not found",{assetId:e}):((0,v.addFileUriTagsToAsset)(i,t.map((e=>e.uri))),this.doneCount+=t.length,this.todoCount-=t.length)}},qb:(e,t)=>(e=_(e.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",uri:"AssetFile.uri"})),(0,c.isNotEmpty)(t)&&(e=e.andWhere("AssetFile.id",">",(0,u.max)(t.map((e=>e.assetFileId))))),e)})}}function _(e){return w.Asset.shownUnhidden(e.from("AssetFile").join("Asset","Asset.id","AssetFile.assetId"))}t.DirectoryTaggerOperation=M},34875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileSync=void 0;const s=i(34996),r=i(46852),n=i(4866),a=i(65548);t.FileSync=class{constructor(e,t){this.root=e,this._ended=!1,this.uri=(0,n.lazy)((()=>(0,r.thenOrElse)(this.root.uri_(),(()=>"file:///"+this.root.posixPath)))),this._progress=(0,n.lazy)((async()=>a.Progress.insertNew({uri:await this.uri(),volume:this.volume}))),this.name="FileSync("+e+")",this.sync=new s.Deferred(this.name).observe(t)}get ended(){return this._ended}end(){this._ended=!0}isDone(){return this.sync.isSettled}donePromise(){return this.sync.promise}get volume(){return this.root.nativePath}async progress(){return(await this._progress()).assignFromPojo({state:this.sync.isPending?"processing":"done"})}}},74015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelDbUpdater=void 0;const s=i(4866),r=i(36079),n=i(91641),a=i(95557),o=i(4691),l=i(17875),u=i(31359),c=i(11944),d=i(39938),h=i(88491),f=i(87748),m=i(6314),p=i(75556),g=i(17078),y=i(42313),v=i(82798),w=i(49374),b=i(30690),S=i(65548),P=i(12474),M=i(58297),_=i(43600),T=i(52257);class E extends a.EndableWrapper{constructor(e){super("ModelDbUpdater",(()=>this.onEnd()),n.EndableRanks.first),this.opts=e,this._done=new m.Latch,this.eta=new u.ETA,this.updatedAssetIds=new Set,this._progress=(0,s.lazy)((()=>S.Progress.insertNew({uri:y.RebuildingURI,volume:"๐Ÿ”„"}))),this.saveSyncProgress=(0,s.lazy)((()=>S.Progress.saveSyncState(this)),h.secondMs),this._outdatedAssetCount=(0,s.lazy)((()=>(0,T.outdatedAssetCount)())),this.run()}async run(){try{if(this.ended||(0,o.ending)())return;if(await w.Library.instanceRequired().ready,this.assetFileUpdateQueue?.ee.on("processed",this.saveSyncProgress),this.logger.info("Starting asset file updates",{afqName:this.assetFileUpdateQueue?.name,afqEnded:this.assetFileUpdateQueue?.ended,afqRunnable:this.assetFileUpdateQueue?.isRunnable(),workStats:this.assetFileUpdateQueue?.p?.stats()}),await(this.assetFileUpdateQueue?.awaitDrain()),this.logger.info("Completed asset file updates",{afqName:this.assetFileUpdateQueue?.name,afqEnded:this.assetFileUpdateQueue?.ended,afqRunnable:this.assetFileUpdateQueue?.isRunnable(),workStats:this.assetFileUpdateQueue?.p?.stats()}),await(this.assetFileUpdateQueue?.end()),this.eta.clear(),await this.saveSyncProgress(),this.ended||(0,o.ending)())return;this.postUpsertQueue=(0,M.mkAssetPostUpsertQueue)(),this.postUpsertQueue?.ee.on("processed",this.saveSyncProgress),this.assetUpdateQueue=await(0,_.mkAssetUpdateQueue)((e=>this.assetUpdater(e))),this.assetUpdateQueue?.ee.on("processed",this.saveSyncProgress),this.logger.info("Starting asset updates",{aqName:this.assetUpdateQueue?.name,aqEnded:this.assetUpdateQueue?.ended,workStats:this.assetFileUpdateQueue?.p?.stats()}),this.logger.info("run(): waiting for asset updates to complete..."),await(this.assetUpdateQueue?.awaitDrain()),await this.saveSyncProgress(),await(this.assetUpdateQueue?.end()),this.logger.info("run(): waiting for asset previews to complete..."),await this.postUpsertQueue.awaitDrain(),await this.postUpsertQueue.end(),await this.saveSyncProgress.refresh(),this.logger.info("run(): finished"),this.ended||(this._done.resolve(),await S.Progress.saveSyncState(this))}catch(e){(0,l.onError)("ModelDbUpdater.run() failed",e),this._done.reject(e)}}outdatedAssetCount(){return this.assetUpdateQueue?.pendingWorkCount()??this._outdatedAssetCount()}async assetUpdater(e){this.updatedAssetIds.add(e);const t=await this.opts.processor({assetId:e,skipPreviews:!0,skipAssetTagging:!0});if(this.logger.info("ModelDbUpdater.assetUpdater("+e+")",{result:t}),(0,P.isUpdateSuccessResult)(t)){this.postUpsertQueue.enqueueWork([{contents:(0,f.stringify)({assetId:e})}]);const i=t?.assetIdsToUpdate;if((0,c.isNotEmpty)(i)){const e=i.filter((e=>!this.updatedAssetIds.has(e)));(0,c.isNotEmpty)(e)&&b.Asset.dbl.runf((t=>t.whereIn("id",e).update({version:0}))),null==this.assetUpdateQueue||this.assetUpdateQueue.ended?this.logger.warn("non-empty assetIdsToUpdate, and AssetQueue is null/ended"):this.assetUpdateQueue.enqueueWork(e.map((e=>({contents:(0,v.toS)(e)}))))}}return t}async onEnd(){await(0,r.endAll)(this.assetFileUpdateQueue,this.postUpsertQueue,this.assetUpdateQueue),this.assetFileUpdateQueue=this.postUpsertQueue=this.assetUpdateQueue=void 0}isNoOp(){return!(0,p.gt0)(this.assetFileUpdateQueue?.processedCount())&&!(0,p.gt0)(this.postUpsertQueue?.processedCount())&&!(0,p.gt0)(this.assetUpdateQueue?.processedCount())}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){if(this.ended||this.isNoOp())return;const e=this._progress();if(this.isDone())return[e.assignFromPojo({state:"done",hed:"Finished rebuilding your library ๐ŸŽ‰",dek:[],completePct:100,incompletePct:0,scanningPct:0})];const t=this.assetFileUpdateQueue;if(null!=t&&!t.isDone()){const i=t.processedCount(),s=t.pendingWorkCount();(0,p.gt0)(t.processRate.msPerEvent)&&this.eta.push((await this.outdatedAssetCount()+s)*t.processRate.msPerEvent);const{completePct:r}=t.percents(),n=this.eta.fmtEstimate(),a="Rebuilding your library"+(0,d.mapNotBlankOr)(n,(e=>", "+e),"โ€ฆ");return[e.assignFromPojo({state:"processing",hed:a,dek:[`Updating file metadata (${(0,g.fmt)(i)} processed, ${(0,g.fmt)(s)} remain)`],completePct:0,incompletePct:r,scanningPct:0})]}if(null!=this.assetUpdateQueue&&null!=this.postUpsertQueue){const t=this.assetUpdateQueue.pendingWorkCount();this.eta.push(t*(this.assetUpdateQueue.processRate.msPerEvent??h.secondMs));const i=t,s=this.assetUpdateQueue.processedCount(),r=s/(i+s),n=(0,p.sigFigs)(100*r,2),a=this.eta.fmtEstimate(),o="Rebuilding your library"+(0,d.mapNotBlankOr)(a,(e=>", "+e),"โ€ฆ");return e.assignFromPojo({state:"processing",hed:o,dek:(0,c.uniq)([`Refreshing assets and previews (${(0,g.fmt)(s)} processed, ${(0,g.fmt)(t)} remain)`]),completePct:n,incompletePct:100-n,scanningPct:0})}}}t.ModelDbUpdater=E},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const s=i(4866),r=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,s.lazy)((()=>(0,r.mkLogger)("sync.PathsToSync")));const w=(0,s.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function b(){const e=[],i=[];for(const s of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.nativePathToUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await b()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const s=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",s),s}},38791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.precheckFiles=void 0;const s=i(13779),r=i(24948),n=i(43414),a=i(3874),o=i(25116),l=i(35280),u=i(39938),c=i(88491),d=i(89253),h=i(75556),f=i(89452);t.precheckFiles=async function(e,t=!0){const i=new Map,m=(0,d.groupBy)(e,(e=>e.dir));for(const[e,t]of m.entries()){const s=await(0,a.nativePath2uri)(e);for(const e of t)for(const t of(0,o.uriEncodingVariants)(s+"/"+e.base))i.set(t,e)}const p=[],g=[],y=Date.now()-n.Settings.syncChangedIntervalMs.valueOrDefault;for(const e of(0,s.batches)([...i.keys()],256)){const t=f.AssetFile.ops().allf((t=>t.whereIn("uri",e)));for(const e of t){const t=i.get(e.uri);if(null==t)(0,r.syncReport)().onProgress({path:(await e.posixFile_())?.nativePath??e.uri,from:"Precheck",state:r.SyncFileStates.failed,details:"Failed to correlate prior AssetFile with requested DirectoryEntry"});else if((0,h.gte)(e.updatedAt,y))(0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.noop,details:"synced "+(0,c.fmtHMS)(Date.now()-e.updatedAt)+" ago",url:(0,l.mkAssetUrl)(e.assetId)?.toString()}),p.push({path:t.nativePath,assetId:e.assetId,assetFileId:e.id});else{const i=await e.whyNotNoop();(0,u.blank)(i)?((0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.noop,details:"in sync",url:(0,l.mkAssetUrl)(e.assetId)?.toString()}),g.push(e.id),p.push({path:t.nativePath,assetId:e.assetId,assetFileId:e.id})):(0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.enqueued,details:"update needed: "+i,url:(0,l.mkAssetUrl)(e.assetId)?.toString()})}}}t&&f.AssetFile.touch(g);const v=new Set(p.map((e=>e.path)));return{fresh:p,stale:e.filter((e=>!v.has(e.nativePath)))}}},65018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressUpdater=void 0;const s=i(28807),r=i(4691),n=i(56958),a=i(67220),o=i(59694),l=i(24603),u=i(65548),c=i(63216);class d extends s.EndableInterval{constructor(e){super({name:"ProgressUpdater",callback:()=>this.onInterval(),intervalMs:(0,u.ProgressRateMs)()}),this.sync=e,this.prior=[]}async onInterval(){if((0,r.ending)()||(0,a.isPaused)())return void(this.prior=[]);const e=await this.sync();if(null==e)return void(this.prior=[]);const t=await u.Progress.saveSyncState(e),i=(0,o.sortBy)(t,(e=>e.uri)).map((e=>e.toSyncState()));(0,l.eql)(this.prior,i)||((0,n.broadcastEvent_)("updateProgress"),await(0,c.runTagMaintenance)(),this.prior=i)}}t.ProgressUpdater=d},23810:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncCompleted=void 0,t.SyncCompleted={syncCompleted:!0}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),b=i(36310),S=i(65548),P=i(71766),M=(0,r.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await S.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),r=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,s.greatestBy)(r,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=r.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=r.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,s.leastBy)(r,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),b.Operation.markOpCompleted({name:b.OperationNames.forceRestartSync}))}function E(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,r.lazy)((async()=>{const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),s=await(0,t.getStaleCompletedAt)(),r=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:r===e.nativePath,status:E(e,s),isNext:e.nativePath===i?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},9515:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncRunner=void 0;const s=i(36079),r=i(91641),n=i(95557),a=i(46852),o=i(79015),l=i(98250),u=i(75123),c=i(6314),d=i(63216),h=i(73571),f=i(85223);class m extends n.EndableWrapper{constructor(e){super("SyncRunner",(()=>this.endCurrentSync()),r.EndableRanks.first),this.fileProcessor=e,this._doneLatch=new c.Latch,this.maybeSetupNextSync()}async progress(){return(0,a.thenMap)(this.currentSync,(e=>e.progress()))}isDone(){return this._doneLatch.isSettled()}donePromise(){return this._doneLatch.promise}endCurrentSync(){const e=this.currentSync;return this.currentSync=void 0,this.currentSyncUri=void 0,(0,s.end)(e)}async setSyncPath(e){if(this.ended)return;await(0,u.clearReaddirCaches)(),(0,o.ee)().emit("clearCache");const t=h.DirectorySync.for({root:l.PosixFile.for(e.nativePath),rootUri:e.uri,fileProcessor:this.fileProcessor});this.syncAndRunNext(e,t)}async syncAndRunNext(e,t){try{const i=this.currentSync=await t;this.currentSyncUri=null==i?void 0:e,null!=i?(this.logger.info("syncAndRunNext(): waiting for completion...",e),await i.donePromise(),this.logger.info("syncAndRunNext(): done",e)):(f.nativePathBlocklist.add(e.nativePath),this.logger.error("syncAndRunNext(): no-op (CHECK ME!)",e))}catch(e){this.logger.error("syncAndRunNext(): caught",{error:e})}return this.maybeSetupNextSync()}async maybeSetupNextSync(){if(this.ended||this._doneLatch.isResolved())return this.logger.info("maybeSetupNextSync(): no-op",{this_ended:this.ended,doneLatch_state:this._doneLatch.state()}),{newPath:null,msg:"ended"};const e=await(0,f.bestPathToSync)();if(null==e)return this._doneLatch.resolve(),this.logger.info("maybeSetupNextSync(): bestPathToSync() returned null, so we're done."),await this.endCurrentSync(),await(0,d.runTagMaintenance)(),{newPath:null,msg:"all paths are synced"};const t=this.currentSyncUri?.nativePath;return null!=t&&t===e.nativePath?{newPath:t,msg:"no-op, current path is already the best"}:(this.logger.info("maybeSetupNextSync(): bestPathToSync() returned a different sync: switching to newBest",{currentSync:this.currentSyncUri,newBest:e}),await this.setSyncPath(e),{newPath:e.nativePath,msg:e.why})}}t.SyncRunner=m},90339:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncService=t.HandledTasks=void 0;const m=i(36079),p=i(28807),g=i(91641),y=i(95557),v=i(4691),w=i(2126),b=i(70259),S=i(37121),P=i(10408),M=i(49379),_=i(90756),T=i(17875),E=i(79141),D=i(79015),k=i(95856),x=i(87489),C=i(79781),F=i(51081),I=i(98250),A=i(24948),O=i(44606),L=i(79403),R=i(62905),N=i(4866),B=i(87308),j=i(69060),z=i(9483),V=i(7162),W=i(19658),U=i(29663),q=i(43414),H=i(14889),G=i(38307),$=i(53719),J=i(76052),K=i(29144),Q=i(11944),Y=i(39938),Z=i(88491),X=i(43947),ee=i(87748),te=i(75556),ie=i(2934),se=i(44726),re=i(82798),ne=i(17146),ae=i(64303),oe=i(49374),le=i(36310),ue=i(13222),ce=i(83148),de=i(20990),he=i(13902),fe=i(87130),me=i(47707),pe=i(93898),ge=i(91877),ye=i(24940),ve=i(63216),we=i(27864),be=i(74015),Se=i(65018),Pe=i(23810),Me=i(9515),_e=i(33206);t.HandledTasks=["runTagMaintenance","checkOperations","repairAsset","repairAssetFile"],t.SyncService=class{constructor(){s.add(this),this.logger=(0,V.mkLogger)("SyncService"),this.progressUpdater=(0,N.lazy)((()=>new Se.ProgressUpdater((()=>this.sync())))),r.set(this,0),n.set(this,new b.Promises("SyncService")),a.set(this,(async e=>{this.logger.info("stdinReceiver",{stdin:e});for(const t of(0,Q.compactBlanks)((0,F.splitLines)(e))){const e=(0,ie.parseJSON)(t),i=(0,se.stripPrefixSuffix)((0,re.toS)(e?.path??e?.file??e?.nativePath??e).trim(),{prefix:"'",suffix:"'"});(0,Y.notBlank)(i)&&(0,G.stdoutWrite)(await this.service.promises.enqueue({name:"processFile",l:()=>this.processFile(i)}))}})),this.processFile=async e=>this.currentPaths().includes(e)?this.logger.throw("processFile(): already processing",{nativePath:e}):(this.logger.info("processFile()",{nativePath:e,currentPaths:this.currentPaths()}),h(this,n,"f").push("processFile",(()=>h(this,s,"m",l).call(this,e,q.Settings.maxRetries.valueOrDefault)),e)),this.taskListeners={name:"SyncService",accept:e=>t.HandledTasks.includes(e.name),apply:async e=>{try{return this.logger.tap({msg:"task complete",level:z.LogLevels.warn,result:await h(this,s,"m",u).call(this,e),meta:{task:e}})}catch(t){throw this.logger.warn("task failed",{task:e,error:t}),t}}},c.set(this,(0,N.lazy)((async()=>{(0,D.ee)().on("updateReadyToInstall",(()=>{this.logger.warn("We're about to upgrade: shut down ASAP!"),(0,w.exit)({reason:"Upgrade is ready--exiting now.",status:0})})),await this.service.setup_(),this.logger.info("setup()",{library:q.Settings.libraryDir.valueOrDefault,exitWhenDone:this.exitWhenDone,argvScanPaths:q.Settings.argvScanPaths.value,scanPaths:q.Settings.scanPaths.value,argv:process.argv}),(0,ne.scheduleFileAndProcCleanups)(),await(0,K.setupShimDelegates)(),(0,ue.installBadShaShim)(),await(0,j.m)(),await(0,S.thenOrTimeout)((0,B.r)(),(0,$.commandTimeoutMs)());const e=oe.Library.instanceRequired();await e.ready;const t=await(0,O.getRemoteOrLocalHealthSummary)();(0,R.isHealthCheckLevelFatal)(t.level)&&await(0,w.exit)({reason:"Health check failed: "+t.msg.join(": "),status:1}),await(0,ve.runTagMaintenance)(),(0,ue.listenForInvalidFiles)(),q.Settings.forceRebuildLibrary.valueOrDefault&&(this.logger.info("setup(): forceRebuildLibrary is true: setting all assets to require updates..."),(0,ae.forceRebuildLibrary)()),q.Settings.forceSync.valueOrDefault&&(await(0,me.rmStatDbDirs)(),(0,D.ee)().emit("clearCache"),le.Operation.ensurePendingOp({name:"forceRestartSync",value:""})),q.Settings.dropWorkQueues.valueOrDefault&&(this.logger.warn("Deleting all prior work queues..."),fe.QueueItem.dbl.runf((e=>e.delete())),(0,D.ee)().emit("clearCache")),await(x.SharedState.instance()?.setup()),await(0,S.thenOrTimeout)((0,ce.checkPendingOperations)(),Z.minuteMs),await this.sync(),this.progressUpdater(),this.service.setInputHandler("--force-rebuild-library",(async()=>{this.logger.warn("--force-rebuild-library requested"),await(0,m.end)(this.modelDbUpdater.clear()),await(0,m.end)(this.sync.clear()),(0,ae.forceRebuildLibrary)(),await this.sync(),(0,G.stdoutWrite)({forceRebuildLibrary:"started"})})),this.service.setInputHandler("--check-sync",(async()=>(0,G.stdoutWrite)({checkSync:await this.maybeRestartSyncOnVolumeChange()}))),this.service.setInputHandler("--cleanup",(()=>(0,ne.cleanup_)())),this.service.setInputHandler("--status",(async()=>(0,G.stdoutWrite)({progress:await((await this.sync())?.progress()),currentPaths:this.currentPaths(),whyDoNotRun:(0,J.whyDoNotRun)()}))),this.service.setInputHandler("--clear-cache",(()=>(0,D.ee)().emit("clearCache"))),W.isTest&&U.onProgressEvt.setShim((async e=>console.log((0,ee.stringify)(e)))),(0,D.ee)().on("volumesChanged",(()=>this.maybeRestartSyncOnVolumeChange())),new p.EndableInterval({name:"SyncService.maybeRestartSync()",callback:()=>this.maybeRestartSync(),intervalMs:Z.hourMs,initialDelayMs:Z.hourMs,rank:g.EndableRanks.first}),new p.EndableInterval({name:"SyncService.setVolumesTTL()",callback:()=>(0,he.setVolumesTTL)(),intervalMs:Z.dayMs/4,initialDelayMs:5*Z.minuteMs,rank:g.EndableRanks.first}),new y.EndableWrapper("SyncService end status",(async()=>this.logger.info("end status",await this.status())),g.EndableRanks.first)}))),this.modelDbUpdater=(0,N.lazy)((()=>q.Settings.noModelUpdates.valueOrDefault?void this.logger.info("modelDbUpdater: skipUpdates is set."):h(this,s,"m",d).call(this,"modelDbUpdater",new be.ModelDbUpdater({processor:ye.handleUpdateCommand}),!0))),this.directoryTaggerOp=(0,N.lazy)((()=>h(this,s,"m",d).call(this,"directoryTaggerOp",new we.DirectoryTaggerOperation))),this.sync=(0,N.lazy)((async()=>{if((0,k.setIsSyncing)(!0),await oe.Library.instanceRequired().ready,q.Settings.argvScanPaths.isEmpty()){const e=this.modelDbUpdater();if(!1===e?.isDone())return e;const t=this.directoryTaggerOp();if(!1===t?.isDone())return t}const e=q.Settings.argvScanPaths.value,t=(0,Q.isNotEmpty)(e)?_e.Syncs.forPaths(e,this.processFile):new Me.SyncRunner(this.processFile);return this.waitForSyncAndCleanup(t),t})),this.exitWhenDone=q.Settings.exitWhenDone.valueOrDefault||q.Settings.argvScanPaths.isNotEmpty(),(0,C.addTaskProcessor)(this.taskListeners),this.service=new de.Service({name:"sync",stdinReceiver:h(this,a,"f")}),h(this,c,"f").call(this).catch((e=>(0,T.onError)(new E.WrappedError("SyncService.setup() failed",{cause:e,fatal:!0}))))}async done(){const e=await this.sync();return null==e||e.isDone()}async status(){const e=await this.sync.prior();return{libraryDir:q.Settings.libraryDir.value,ending:(0,v.ending)(),done:await this.done(),sync:e?.name,progress:await(e?.progress()),summary:L.HealthCheck.summary(),jobs:this.service.promises.stats(),processCount:h(this,r,"f")}}currentPaths(){return h(this,n,"f").pendingWithName("processFile").map((e=>e.payload))}async cancelSync(){const e=await this.sync();null==e||e.isDone()?this.logger.info("cancelSync(): No sync to end."):(this.logger.info("cancelSync(): ending current sync..."),await e.end())}async restartSync(){return await(0,m.end)(this.sync.clear(),Z.minuteMs),this.sync()}async maybeRestartSyncOnVolumeChange(){const e=await this.sync.prior();if(null==e||e instanceof Me.SyncRunner){if(null==e||e.ended||e.isDone())return this.logger.info("maybeRestartSyncOnVolumeChange(): prior sync ended, restarting..."),await this.sync.refresh(),"refresh";{this.logger.info("maybeRestartSyncOnVolumeChange(): calling maybeSetupNextSync()...");const t=await e.maybeSetupNextSync();return(0,ee.stringify)(t)}}return this.logger.info("maybeRestartSyncOnVolumeChange(): no-op, current sync is "+e.name),"noOp:"+e.name}async maybeRestartSync(){const e=this.sync.lastSetAgoMs();if((0,te.lt)(e,H.ShortCommandTimeoutMs))return void this.logger.info("maybeRestartSync(): sync was touched recently.",{lastSetAgoMs:e});const t=await this.sync.prior();t instanceof Me.SyncRunner&&t.ended?(this.logger.info("maybeRestartSync(): SyncRunner ended. Restarting."),this.sync.refresh()):this.logger.info("maybeRestartSync(): We're busy doing something else or the current SyncRunner hasn't ended. no-op.")}async waitForSyncAndCleanup(e){try{await(0,X.delay)(Z.secondMs),await(e?.donePromise()),await(0,X.delay)(Z.secondMs),await this.service.promises.awaitSettled(),await h(this,n,"f").awaitSettled(),await(0,ve.forceRunTagMaintenance)(),W.isTest&&(0,G.stdoutWrite)(Pe.SyncCompleted),(0,k.setIsSyncing)(!1),this.exitWhenDone&&await(0,w.exit)({reason:"Finished",status:0})}catch(e){(0,k.setIsSyncing)(!1),this.exitWhenDone?await(0,w.exit)({reason:"Error: "+e,status:13}):this.logger.error("Sync error",e)}}},r=new WeakMap,n=new WeakMap,a=new WeakMap,c=new WeakMap,s=new WeakSet,o=function(){var e;f(this,r,(e=h(this,r,"f"),++e),"f"),h(this,r,"f")%50==0&&(0,ne.cleanup_)()},l=async function e(t,i){this.logger.info("#processFile()",{nativePath:t,retries:i});try{const r=await(0,pe.importFileToResult)(I.PosixFile.for(t));return W.isTest&&(0,G.stdoutWrite)(r),(0,ge.isErrorResult)(r)?(this.logger.warn("#processFile() error result",{nativePath:t,result:r,retries:i}),!1!==(0,M.isRetriableError)(r.error)&&i>0?h(this,s,"m",e).call(this,t,i-1):r):r}catch(r){this.logger.error("#processFile() caught error",{nativePath:t,retries:i,error:r});const n=(0,E.toWrappedError)(r,{path:t});return!1!==r.retriable&&i>0?(await(0,X.delay)(q.Settings.minDelayBetweenRetriesMs.valueOrDefault),h(this,s,"m",e).call(this,t,i-1)):((0,T.onError)("Failed to process file "+t,{we:n}),{path:t,state:A.SyncFileStates.failed,error:(0,P.errorToS)(n)})}finally{h(this,s,"m",o).call(this)}},u=async function(e){return this.logger.info("enqueueing task",{task:e}),h(this,n,"f").enqueue({name:"#handleTask("+e?.name+")",l:async()=>{switch(await oe.Library.instanceReady(),this.logger.info("handling task",{task:e}),e.name){case"runTagMaintenance":return await(0,ve.runTagMaintenance)(),"success";case"checkOperations":return await(0,ce.checkPendingOperations)(),"success";case"repairAsset":const t=e;return await(0,ye.handleUpdateCommand)({forceSync:!0,skipPreviews:!1,forceRebuildPreviews:!0,...t.args[0]}),"success";case"repairAssetFile":const i=e;return await(0,ye.handleUpdateCommand)({forceSync:!0,...i.args[0]}),"success";default:throw new _.InternalError("unexpected task: "+(0,ee.stringify)(e))}}})},d=function(e,t,i=!1){if(null!=t)return h(this,n,"f").push(e,t.donePromise()).then((()=>{this.logger.info(e+" completed.")}),(t=>(0,T.onError)(e+" failed",t))).finally((async()=>{i&&await h(this,n,"f").push("forceRunTagMaintenance",(0,ve.forceRunTagMaintenance)()),this.sync.refresh()})),t}},33206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Syncs=t.syncForPath=void 0;const s=i(36079),r=i(91641),n=i(95557),a=i(17875),o=i(98250),l=i(24948),u=i(4866),c=i(39938),d=i(6314),h=i(66776),f=i(39784),m=i(73571),p=i(34875),g=i(6492);async function y(e,t){if((0,c.blank)(e))return;const i=o.PosixFile.for(e);if(await i.isDirectory()){const s=await(0,g.posixFileToUriPath)(i);return null==s?((0,l.syncReport)().onProgress({path:e,from:"syncForPath()",state:"failed",details:"Cannot import: URI path could not be built for that path."}),void await(0,l.syncReport)().close()):m.DirectorySync.for({root:i,rootUri:s.uri,fileProcessor:t})}return new p.FileSync(i,t(e))}t.syncForPath=y;class v extends n.EndableWrapper{static forPaths(e,t){return new v("import paths fs sync",(0,f.toA)(e).map((e=>()=>y(e,t))))}constructor(e,t){super(`Syncs(${e})`,(()=>(0,s.end)(this.currentSync)),r.EndableRanks.first),this.laters=t,this._done=new d.Latch,this.run=(0,u.lazy)((async()=>{try{for(const e of this.laters){const t=await e();null!=t&&(this.currentSync=t,await t.donePromise())}this._done.resolve()}catch(e){(0,a.onError)("Syncs.run() failed",e),this._done.reject(e)}})),this.run()}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){return(0,h.map)(this.currentSync,(e=>e.progress()))}}t.Syncs=v},52257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdatesForUri=t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.currentUriRoots=void 0;const s=i(7162),r=i(93813),n=i(6667),a=i(3874),o=i(55713),l=i(46573),u=i(11944),c=i(26588),d=i(82798),h=i(30690),f=i(89452),m=i(36310),p=i(35735);function g(e,t){return e.upsertWorkItems(t.map((e=>({contents:(0,d.toS)(e)}))))}async function y(){return[...await(0,c.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(d.toS)}async function v(e){const t=(0,s.mkLogger)("enqueueAssetFileUpdatesForUri("+e+")"),i=p.Queue.ops().upsertOne({name:(0,p.assetFileUpdatesQueueName2uri)(e)});await m.Operation.applyOnce({name:m.OperationNames.enqueueAssetFileUpdates,version:r.AssetFileVersion,value:e},(()=>{t.info("starting",{queue:i.name}),f.AssetFile.dbl.pluckBatched({onResults:e=>g(i,e),qb:(t,i)=>(t=t.select("id").orderBy("id","asc").where("version","<",r.AssetFileVersion).andWhereLike("uri",e+"%"),(0,u.isNotEmpty)(i)&&(t=t.andWhere("id",">",(0,n.max)(i))),t)})}));const a=i.itemCount();return t.log(0===a?"debug":"info","Added outdated assetFiles:",{queue:i.name,assetFileCount:a}),a?i.name:void 0}async function w(e){const t=(0,s.mkLogger)("enqueueAssetUpdatesForUri("+e+")"),i=p.Queue.ops().upsertOne({name:(0,p.assetUpdatesUri2QueueName)(e)});await m.Operation.applyOnce({name:m.OperationNames.enqueueAssetUpdates,version:r.AssetVersion,value:e},(()=>(t.info("starting",{queue:i}),h.Asset.dbl.pluckBatched({onResults:e=>g(i,e),qb:(t,i)=>(t=t.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","<",r.AssetVersion).andWhereLike("AssetFile.uri",e+"%"),(0,u.isNotEmpty)(i)&&(t=t.andWhere("Asset.id",">",(0,n.max)(i))),t)}))));const a=i.itemCount();if(0!==a)return t.info("Added outdated assets:",{queue:i.name,assetCount:a}),i.name}t.currentUriRoots=y,t.enqueueAssetFileUpdates=async function(){return(0,c.thenCollect)(y(),v)},t.outdatedAssetCount=async function(){const e=await y();return h.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","<",r.AssetVersion).andWhere((t=>e.forEach((e=>t.whereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){return(0,c.thenCollect)(y(),w)},t.enqueueAssetUpdatesForUri=w},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const s=i(3874);async function r(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=r,t.posixFileToUriPath=async function(e){return r(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return r(e,(0,s.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const s=i(7162),r=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,s.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const s=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,r.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=s.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,r.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),s=Date.now()-i;if(sh(e)))}},63216:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const r=s(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),E=i(8199),D=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),A=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return A().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),s=Date.now(),r=A().addContext(".runTagMaintenance()");r.info("starting",{ctx:i});try{r.info("validating all tags..."),C.Tag.validate_(),r.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(r.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),r.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),r.info("vacuuming orphan tags..."),await L()}catch(e){A().warn("runTagMaintenance() failed",e)}const n=Date.now()-s,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),A().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const s=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(s)?(e.maybeUpsertDisplayName(s),i.info("updated tag",{id:e.id,path:e.path,displayName:s}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const s=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:s}),null!=s?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(s.label)?s.label.trim():"/"===s.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(s.mountpoint,{prefix:r.default.sep,suffix:r.default.sep}),r.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},22286:e=>{"use strict";e.exports=require("node:https")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=54620);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:s,PasetoNotSupported:r}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new s("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new r("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new r("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new s("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const s=i(79551);e.exports={decode:s}},77308:(e,t,i)=>{const s=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:r,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+s(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+s(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==r){if("string"!=typeof r)throw new TypeError("options.issuer must be a string");c.iss=r}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:s}=i(74485),r=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new s("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new s("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new s("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new s("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new s("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new s("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?r(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new s("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new s("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new s("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new s("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new s("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new s("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new s("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new s("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new s("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new s("missing iat claim");if(m+r(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const s=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(s(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const s=i(77308),r=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!r(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=s(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),s=Buffer.from(i,"base64"),r=2+(1&s[s.length-1]);return Buffer.concat([Buffer.alloc(1,r),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const s=i(39084),{PasetoInvalid:r}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,s,r,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return s?{payload:r,footer:a?.length?a:void 0,version:e,purpose:l}:r}const u=o(r);return n(i,u),s?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new r(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{s(o<=2),i=a(i),n=a(n)}catch{throw new r("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const s=i(6113),r=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=s,c=r.promisify(s.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>s.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,s)=>u[e]({name:"AES-CTR",counter:s,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:r.promisify(s.sign),verify:r.promisify(s.verify),"v1.local-encrypt":async function(e,t,i){const r="v1.local.",o=m(e,s.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(r,o,p,t),v=m(y,f);return a(r,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const s=e.subarray(0,32),r=e.subarray(-48),a=e.subarray(32,-48),u=s.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",s,a,t),v=m(g,p);if(!l(r,v))throw new o("decryption failed");const w=await y(a,f,s.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,r){const o="v3.local.",l=s.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),S=n(o,l,w,t,r),b=m(S,p);return a(o,t,l,w,b)},"v3.local-decrypt":async function(e,t,i,s){const r=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,r]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,r]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),S=n("v3.local.",r,u,t,s),b=m(S,g);if(!l(a,b))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:s}=i(6113);let{isKeyObject:r}=i(35740);r||(r=e=>null!=e&&e instanceof s),e.exports=r},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:s}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new s("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,r=Buffer.allocUnsafe(8);return r.writeUInt32LE(t,4),r.writeUInt32LE(i,0),r}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const s=i.exec(e);if(!s)throw new TypeError(`invalid time period format ("${e}")`);const r=parseFloat(s[1]);switch(s[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*r);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*t);case"day":case"days":case"d":return Math.round(864e5*r);case"week":case"weeks":case"w":return Math.round(6048e5*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*r)}}},45018:(e,t,i)=>{const{encode:s}=i(87536);e.exports=function(e,t,...i){let r=`${e}${s(Buffer.concat(i))}`;return t.byteLength&&(r+=`.${s(t)}`),r}},97540:(e,t,i)=>{const s=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=s(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=s(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:s}=i(74485),{strict:r}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return r(n(t)),t}catch{throw new s("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:s}=i(45112),r=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=r(u,e,t,i,l),d=await s(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:s}=i(6113),r=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!r(t))try{t=s(t)}catch{}if(!r(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:s}=i(6113),r=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return s(r(e,i),r(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:s}=i(74485),{verify:r}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await r(i,p,l,m))throw new s("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const s=i(74485),r=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:r,V2:n,V3:a,V4:o,errors:s}},34089:(e,t,i)=>{const{"v1.local-decrypt":s}=i(45112),r=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=r(t)).export(),h=await s(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const s=i(25054),r=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=r(t);const u=s(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const s=i(54773),r=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:s,verify:r,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const s=i(6113),{promisify:r}=i(16464),{PasetoNotSupported:n}=i(74485),a=r(s.generateKeyPair),o=r(s.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:s,RSA_PSS_SALTLEN_DIGEST:r},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:s,saltLength:r})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:s,RSA_PSS_SALTLEN_DIGEST:r},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:s,saltLength:r});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const s=i(83985),r=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:s,verify:r,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const s=i(39084),r=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(r.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:s}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(s).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=r.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return r.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),s.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=r.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),s.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=r.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const s=i(25054),r=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=r(e,a);t=o(t);const u=s(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const s=i(80094),{_checkPublicKey:r}=i(42421),{post:n}=i(97362),a=r.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:r=!1,...o}={}){t=a(t);const{m:l,footer:u}=await s("v2.public.",e,void 0,64,t);return n("v2",r,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":s}=i(45112),r=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=r(t);const f=n(u),m=t.export(),p=await s(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const s=i(25054),r=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=r(t);const d=s(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const s=i(38681),r=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:s,verify:r,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const s=i(6113),{promisify:r}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=r(s.generateKeyPair),u=r(s.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return s.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return s.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return s.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:s}=i(6113),r=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=r(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=s(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:s}=i(6113),r=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=r(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const s=i(54294),r=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:s,verify:r,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:s,_checkPublicKey:r,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:s,_checkPublicKey:r,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const s=i(25054),r=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=r(e,u),d=n(o);t=l(t);const h=s(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const s=i(42417),r=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=s(l),{m:d,footer:h}=await r("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const s=i(4866),r=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,s.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,s.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const s=i(11944),r=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=s.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,s.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,s.isEmpty)(e))return{index:-1,value:void 0};let r,n=-1;for(let s=0;se.slice(i,i+t)))}async function k(e,t){return(0,s.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const s=e[i];if(null!=s&&!0===await t(s))return s}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const s of e){i++;try{if(null!=s){const e=await t(s,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,s.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let s=i;s<=e.length-1;s++)if(t(e[s]))return s},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,s.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,s.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],s=[];let r=0;for(const n of e)(t(n,r++)?i:s).push(n);return[i,s]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,s.compact)((0,s.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const s=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,s.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const r=[];for(const n of D((0,s.compact)((0,f.toA)(e)),t))r.push(...(0,s.compact)(i(n)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const n of D((0,s.compact)((0,f.toA)(e)),t))r.push(...(0,s.compact)(await i(n)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,s)=>(0,d.tap)(t(e,s,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const s of e){const e=i.find((e=>e.some((e=>t(s,e)))));e?e.push(s):i.push([s])}return i},t.clusterEvery=function(e,t){const i=[];for(const s of e){const e=i.find((e=>e.every((e=>t(s,e)))));e?e.push(s):i.push([s])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const s of e){for(const e of i)if(null!=s&&await k(e,(e=>t(s,e)))){e.push(s);continue e}null!=s&&i.push([s])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[s],(e=>i(e,s))))return s}{const s=t+r;if(se+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=s(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const s=t;s.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),s.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),s.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),s.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),s.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),s.on("noTaskData",((e,i,s)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),s.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const s=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new s.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const s=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,s.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,s.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const s=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,s.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const s=i(97461);class r{constructor(e=[],t=s.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let s,r=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(n);null!=e&&(s=e,r=a)}}return s}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const s=i(21941);let r=!(0,s.noColor)();function n(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,s.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const s=i(59694),r=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,s.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,s.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,s.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[s,r]of this.m.entries()){const n=e(s);t.fill(n,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const s=i(4866),r=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,s.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,s.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const s=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,s.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const s=i(24603),r=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,s.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,s.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,s.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,s.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,s.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const s=i(39653),r=i(4866),n=i(98250);t.examples=(0,r.lazy)((()=>n.PosixFile.for((0,s.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const s=i(4866),r=i(40786),n=i(3955);t.examplesNativePath_=(0,s.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const s=i(47261),r=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[s.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,s.set(this,0),r.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,s,l(this,s,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,s,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,s,(a=l(this,s,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,s,(o=l(this,s,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,s,(i=l(this,s,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,s,0,"f"),u(this,r,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const s=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,s),(0,c.gt0)(this.opts.timeoutMs)&&s.setTimeout(this.opts.timeoutMs),s.promise.then((e=>{this.set(i,e)}),(e=>{var t,s;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(s=l(this,o,"f"),++s),"f")})),s.promise}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class s{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=s},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,s.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const s=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,s).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let s,o=0;for(;null!=(s=t.exec(this.headerRow));){const l=this.headerRow.substring(o,s.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:s.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(s.index,t.lastIndex),d=s.index+((0,c.indexOfNonSpace)(u)??0),h=s.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:s,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,s.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const s=i(66776),r=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,s.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,s]=p(e,t);return{lat:i,lon:s}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,s.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,s=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(s)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,s=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return s(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const s=i(4866);t.isSuspended=(0,s.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const s=i(93977),r=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,s.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const s=i(889),r=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(s.ExifDateTime,s.ExifDate,s.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,s.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),s.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,s,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,s=await t;if(!(0,l.eql)(i,s))for(const e of this.watchers)e(s);null!=this.ttlMs&&this.ttlMs>0&&void 0!==s&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,s.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,s.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const s=i(70612),r=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,s.arch)(),platform:(0,s.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const s=i(4866),r=i(74269),n=i(78109);t.rootLoggers=(0,s.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,s.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const s=i(11944),r=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,s.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,s.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,s.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,s]of e)t[i]=s;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,s])=>t(i,s)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const s=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const n=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,s.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,s.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const s=i(97742),r=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,s.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,s.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const s=i(38625);t.noColor=function(){return(0,s.toBoolean)(process.env.PS_LOG_COLOR)??(0,s.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=s(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const s=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=s&&s>0&&null!=r&&r>0?i(s,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),s=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,s,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let s=0;se/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,s.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,s.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let s=0;const r=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const s=i(11944),r=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[s,r]of(0,u.entries)(e)){const e=t(s,r);null!=e&&(i[s]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,s.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,s]of p(t))null==e[i]&&(e[i]=s);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,s]of(0,u.entries)(t))null==e[i]&&(e[i]=s);return e},t.pickMap=function(e,t,i){const s={};for(const r of t)s[r]=i(r,e[r]);return s},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const s={};let r=0;for(const n of(0,u.keys)(e))if(s[n]=t(n,e[n]),r++,(0,l.gt)(r,i))break;return s},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const s of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[s]=e(t[s]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,s)=>i.includes(t)?void 0:e(s,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,s.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const s=i(17718),r=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return S()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,s]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[s]}const x=(0,a.lazy)((()=>(0,s.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const s=i(5712),r=i(39784),n=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(s.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,s.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),n=s(i(17718)),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),E=i(4586),D=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),A=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),O=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),s=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(s)&&Math.abs(i-s){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))A().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,s=await this.pidfiles(),r=await this.pids(s??[]);if((0,l.isEmpty)(r))return A().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of s){const s=await r.readJson();if(null==s){A().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=s.pid;if(!(0,h.gt0)(l)){A().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:s,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(s,u)){A().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:s,pidEntry:u}),await r.unlink("debug"),n.push(s);continue}const c=(0,h.gt0)(s.timeoutMs)?s.startTime+s.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(s.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(A().info("killOldProcs(): killing",{reason:d,json:s}),a.push(N(l,i,!1)),n.push({...s,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const s=e.pid;if(!(0,h.gt0)(s))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,r.pidExists)(s)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),s=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),n={...e,cmd:s,startTime:r};return await i.writeJson_(n),A().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void A().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{A().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=s(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const s=i(9678),r=i(7162),n=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?s.SimpleShortAppName:s.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const r=s(i(97742)),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),S=i(46852),b=i(69317),P=i(9288),M=i(51053),_=i(71663),T=(0,n.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],A))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const A={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},O=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",O.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,A),s=(0,d.onlyReqValued)((0,p.parseFixed)(O,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return s.find((e=>e.pid===r.default.pid))||s.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),s}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,b.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...A,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const s=i(6231),r=i(3331);t.safeRandomChars=function({radix:e=s.TokenRadix,length:t}){return(0,r.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,r.decuss)((()=>(e?.radix??s.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const s=i(43947),r=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,s.delay)(1).then((()=>e))}return async function(...s){f=!0,m=Date.now()+(0,n.max_)(t,i);const r=d=new a.Deferred(c);(0,n.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...s))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const s=i(61570),r=i(82798);function n(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,s.pick)(r,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const s=[];for(const t of e)try{s.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{s.push(n(t))}const r=0===s.length?t.NothingRegExp:s.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",s=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,s||(s=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,r.toS)(t));return new RegExp(i,t??(s?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=s(i(70612)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const s=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:s,error:i}),s)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=s(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const s=i(39784);function r(e){return e instanceof Set?e:new Set((0,s.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,s.toA)(e.keys()).every((e=>t.has(e)))&&(0,s.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const s=i(7127),r=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=s.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const s=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,s.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const s=i(87748),r=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,s.stringify)(e))}){let o;const l=async i=>{const s=Date.now(),r=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-s),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const s=i(88491);t.ShortCommandTimeoutMs=7*s.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),r=this.valueOf(this.store[s]);if(e===r)return{found:!0,index:s};e>r?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,s.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const s=i(97742),r=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(s.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const s=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(s.stdout)}},38307:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=s(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:s}){if(null==s||(0,d.streamEnded)(s))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);s.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?s.write(u.FailStr+"\n"):s.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const s=String(e);return s+(0,l.padding)(i,t-s.length)},t.padReplace=function(e,t,i,s){return(0,c.strslice)(e,0,t)+(0,l.padding)(s,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,s=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,s);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const s=Math.min(Math.ceil(e.length/t),i??e.length)-1;return s<=0?[e]:[...(0,o.times)(s,(i=>e.slice(i*t,(i+1)*t))),e.slice(s*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const s=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,s)+e.substring(s+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:s}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const s=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(s.slice(-r.length),r,i)?s.slice(0,-r.length):s},t.gist=function(e,t=80,i=80){const s=(0,h.toS)(e),r=s.length-(t+i);return r<=0?s:s.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+s.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,s.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,s.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),s=e.toLowerCase(),r=t.indexOf(s);if(r>=0)return{index:r,match:s}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],s=[];let r,n=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(n,r.index)),s.push(e.substring(r.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,s.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,s.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let s=0;s4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const s of(0,d.toA)(e))if(null!=s&&!(0,n.blank)(s))for(const e of s.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const s=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>s.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const s=i(82798);function r(e){return(0,s.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,s.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,s.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=s(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,s=224){return i.encodeBuffer(o(e,s)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,s=224){return l(e,t,i,s)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const s=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,s.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let s=0,r="";for(let n=0;n=s&&(s=i.get(n,a),r=(0,l.substr)(e,n-s+1,s)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const s=e.normalize(),r=t.normalize();return e!==s||t!==r?y(s,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,s)=>i===t.charAt(s)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),s=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===s?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(s);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const n=Math.min((0,s.count)(e,(e=>e===i)),(0,s.count)(t,(e=>e===i)));(0,a.times)(n,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,s.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,s.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,s]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return b(i,s,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,s]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,s,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let s=Math.max(e.length,t.length);s>=0;s--){const r=(0,a.mapNumericOr)(e.charCodeAt(s),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(s),(e=>e),256),o=(0,a.clamp)(-256,256,r-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,s.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,s.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const s=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,s.stringify)((0,r.sortedKeys)(e))}},55646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const s=i(75556);class r{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,s.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=r},3917:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){s.add(this),this[c]="TTLMap",r.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,s,"m",u).call(this)),e),"f"),d(this,s,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,s,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,s,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,s,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,s,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,s,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,s,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,s,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,s,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,s,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){s.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,s,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,s,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,s,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,s,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,s,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,s,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,s,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,s,"m",n).call(this),[...this.delegate.keys()]}[(s=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,s,"m",r).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const s=i(4866),r=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,s.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=s(i(70612)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",s.set(this,new Map)}clear(){return a(this,s,"f").clear(),this}delete(e){return a(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,s,"f").delete(t)}get(e){const t=a(this,s,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,s,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,s,"f").get(e)?.deref();if(null!=i)return i;const r=t();return null!=r&&this.set(e,r),r}set(e,t){return a(this,s,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,s,"f").get(e)?.deref()}get size(){return a(this,i,"m",r).call(this),a(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries())null==i.deref()?a(e,s,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries()){const r=i.deref();null==r?a(e,s,"f").delete(t):yield r}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,s,"f").entries()){const r=i.deref();null==r?a(e,s,"f").delete(t):yield[t,r]}}()}[(s=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,r=function(){for(const[e,t]of a(this,s,"f").entries())null==t.deref()&&a(this,s,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const s=i(88491),r=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*s.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+s.dayMs,e))).map((e=>new Date(e))).get()}},46080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const s=i(39784),r=i(13779),n=i(1440),a=i(43414),o=i(67654),l=i(92356);t.aggregateAssetFiles=async function(e){const t=(0,s.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?r.clusterSome:r.clusterEvery)(t,o.isSimilarAssetFile)}},67654:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(24603),o=i(66776),l=i(75556),u=i(61570),c=i(17078),d=i(84593),h=i(85563),f=i(7162),m=i(34928),p=i(72461),g=i(32148),y=i(43414),v=i(65642),w=i(74873),S=i(27446),b=(0,s.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,s=((e,t)=>[e,t])){const r=e[i],o=t[i];if((0,n.blank)(r)||(0,n.blank)(o)||(0,a.eql)(r,o))return;const[l,u]=s(r,o);return(0,a.eql)(l,u)||(0,a.eql)(r,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${r} โ‰  ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const s=(0,w.findInequalFields)(e[i],t[i]);return null==s?void 0:`Different ${i} (${s.aKey}:${s.aValue} โ‰  ${s.aKey}:${s.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void b().debug("matching SHA",{af1:e,af2:i});const s=(0,S.isVideoMimeType)(e.mimetype),n=(0,S.isVideoMimeType)(i.mimetype);if(s!==n)return b().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:s,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),s=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,s,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void b().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};b().debug("whyNotSimilar()",{fields:k});const x=(0,r.compact)((0,u.values)(k));if((0,r.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),s=(0,p.toImageHash)(i);if(null!=t&&null!=s){const e=(0,g.compareImageHashes)(t,s,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos โ‰  images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const s of i)if(s.id!==t?.id){const t=E(e,s);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const s=i(4866),r=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,s.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function S(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function b(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):S(t)}async function P(e){const[i,s,r,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...s,...r,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=S,t.assetFileImageHashFields_=b,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const s=i.capturedAt.toAssetFileFields();return null==s?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...s,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),b(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),S=i(19209),b=(0,s.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=S.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const s=P.indexOf(t.scheme);if(null==s)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:s,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(r),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return b().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return b().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return b().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const s=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,s.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=s(i(92332)),n=i(75556);t.debounce=function(e,t){let i,s=[];const a=(0,n.gt0)(t)?(...n)=>{s=n,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...s)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),E=i(46234),D=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,S.defer)((()=>(0,k.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const s=i[e];if(s.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield s}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;s.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,s=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,s,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,s,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,r=A,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},47284:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const s=i(6314),r=i(95557);class n extends r.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new s.Latch}isDone(){return!this.doneLatch.isPending()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,s.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const s=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:s});try{await(0,o.thenOrTimeoutError)(i.end(),s,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,s.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,s,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),s.add(this),this.opts=e,r.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,s,"m",a).call(this);const h=()=>{u(this,s,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,s,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,n=new WeakMap,o=new WeakMap,s=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const s=i(84253);t.EndableRanks=(0,s.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,s.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,s,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,s,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,r,"f").call(this)}},s=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const s=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=s.isTest?e:e||r}},2126:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=s(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const s=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(s)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5685:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(89253),a=i(82798),o=i(59387),l=i(70259);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,s.set(this,new n.MultiMap),this.p=new l.Promises(e,t)}vacuum(){r(this,s,"f").filterInPlace(((e,t)=>!t.signal.aborted))}enqueue(e,t){for(const t of r(this,s,"f").get(e)??[])t.abort();this.vacuum();const i=new AbortController;return r(this,s,"f").add(e,i),this.p.serial((0,a.toS)(e),(()=>t(i)))}},s=new WeakMap},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,s)=>{t=e,i=s})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:s}){return new v(e,t,i,s)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),s.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,s,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,r,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,s,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,s,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,s=new WeakSet,u=async function(e,t){var i;const s=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===s&&h(this,a,i,"f"),d(this,o,"f")?.id===s&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,s,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const s=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new r.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,s.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,s.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const s=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:r):(n=!0,r=(0,s.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const s=i(11944),r=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,s.compact)(await e);return(0,s.isEmpty)(t)?[]:(0,s.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const n=[];for(const a of(0,s.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,s.compact)(await e);if((0,s.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,s.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const s=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);s.push(...await P(i(e)))}return s},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,s.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,s.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:r,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:r,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:n}){return(await T({name:e,arr:(0,s.compact)(t),f:i,maxConcurrent:r,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),s=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,s)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let s,r=null;try{s=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??s)}catch{}if(null!=r)throw r;return s},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const s=await e;if(null==s)return;const r=await t;return null!=r?i(s,r):void 0},t.thenMapOr=async function(e,t,i){const s=await e;if(null==s)return i();const r=await t(s);return null==r?i():r},t.thenMap2Or=async function(e,t,i,s){const r=await e;if(null==r)return s();const n=await t;if(null==n)return s();const a=await i(r,n);return null==a?s():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const s of e){i++;try{if(null==s)continue;const e=await t(s,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const s=await T({name:e,arr:t,f:i});return(0,r.sortBy)(s,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const s=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-s)+"ms")),r);try{const r=await(0,c.tot)(t),n=Date.now()-s;return i?.(r,n),this.push(e,n),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-s),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),s=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...s])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,s.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),s=t();return _(e,Date.now()-i),s},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,s.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){s.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const n=d(this,s,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,s,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,s,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,l=function({name:e,l:t,payload:i,serialId:s}){const r=new P.Deferred(e,{payload:i,serialId:s});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},39506:function(e,t){"use strict";var i,s=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return r(this,i,s(this,i,"f").catch().then(e),"f")}},i=new WeakMap},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const s=i(41135),r=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,s.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,s.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const s=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,s.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,s.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const s=i(38625),r=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:s,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const s=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,n.delay)(s,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:s.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=s(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,n.lazy)((()=>new Set((0,o.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:s=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...E(s),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,s]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(s))}return r}t.childEnv=k},69317:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=s(i(17718)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),E=i(79141),D=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function A(e,i,s,r=0){const a=new Date,o=[];return(0,b.niceable)(i,s)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,s){const n=(0,x.spawnOptions)(s);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),A(r.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const s=i.quiet??!1,r=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const S=new d.Latch;null==a.stdout?S.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==a.stderr||r?b.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!s&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,s){const n=(0,x.spawnOptions)(s);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),A(r.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const s=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(s.result),meta:{cmd:e,args:t,opts:i,result:s}})}},95237:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=o(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),S=i(7162),b=i(91464),P=i(36079),M=i(91641),_=i(49379),T=i(98462),E=i(90524),D=i(94845),k=i(51053),x=i(69317),C=i(24905),F=i(52289),I=i(95298),A=(0,c.lazy)((()=>(0,S.mkLogger)("child.ChildService")));async function O(e){const t=(0,b.ensureSuffix)(e,".js"),i=T.BaseFile.projectRoot(),s=T.BaseFile.for(u.default.cwd()),r=(0,D.isPacked)()?[i.join("bin",t),k.isElectron?i.join("app.asar",t):void 0]:[s.join("dist","library",t),s.join("dist","core",t),s.join("lib","library",t)];r.push(s.join("dist","app",t));for(const e of r)if(null!=e&&!0===await e.isNonEmptyFile((0,D.isPacked)()?p.KB:128))return A().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:D.isPacked,paths:r.map(v.toS)}});return A().throw("Failed to find path to "+e,{paths:r,fatal:!0})}t.pathToService=O,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class L{static async mk_(e,t={}){const i=t.pathToService??await O(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new L(e,i,t)}constructor(e,t,i){s.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,F.serviceExitTimeoutMs)(e),this.logger=(0,S.mkLogger)(this.name);const o=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&o.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,x.spawn)(u.default.execPath,o,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,s,"m",n).bind(this),onStderr:a(this,s,"m",r).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(E.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,b.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=L,s=new WeakSet,r=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const s=i(55568),r=i(43414),n=i(14889);t.serviceExitTimeoutMs=function(e){return(0,s.isSyncService)(e)?r.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),E=i(45512),D=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){s.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,r,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,s,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,s,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,s,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,s,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,s,"m",n).call(this),this._stopped=!1,u(this,s,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,s,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,s=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,s,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,s,"m",n).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,s,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,s,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const s=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(s))return a.join("$library",i.posixPathFrom(s));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(7304),r=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(s.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,r.exit)(0)})),e.parse(r.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const s=i(51081),r=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,s.joinLines)(...(0,r.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const s=i(97742),r=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(s.env.maxLineLen)??s.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const s=i(43414),r=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(s.Settings.logColor.envValue=!1),(0,r.map)(e.color,(e=>s.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const r=s(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(r.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const s=i(43414),r=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,r.isTrue)(e.timing)&&(s.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const s=i(4866),r=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const s=(0,a.toGt0)((0,l.env)()[t]);return null==s||i.includes(s)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${s}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,s.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const s=i(43414),r=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,r.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(s.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,r.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const s=i(4866),r=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,s.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const s=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:s,closeLabhashes:[s],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function S(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,s.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return S((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=S;const b=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(b,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const s=(0,c.unlabhash)(e),n=S(s);return null!=s&&null!=n&&((0,r.pushUniq)(n.closeLabhashes,e),(0,r.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(s))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const s=i(4866),r=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],s=[];for(let r=0;re>b?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-s)])}function _(e){const[t,i,s]=v(e),r=(t+16)/116,n=i/500+r,a=r-s/200,o=n*n*n,l=a*a*a,u=o>b?o:(116*n-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>b?l:(116*a-16)/P;return[u*S.X,c*S.Y,d*S.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,s.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,s]=(0,f.clampRGB)(e),r=Math.max(t,i,s),n=r-Math.min(t,i,s),a=n?r===t?(i-s)/n:r===i?2+(s-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),r?n/r*100:0,r/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,s]=e,r=(200-i)*s/100;return[t,r>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,r/2]}function I(e){const[t,i,s]=e,r=i*(s<50?s:100-s)/100;return[t,r>0?2*r/(s+r)*100:0,s+r]}function A(e){const t=e[0]/360*6,i=e[1]/100,s=e[2]/100,r=Math.floor(t),n=s*(1-i),a=s*(1-(t-r)*i),o=s*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[s,a,n,n,o,s][l],255*[o,s,s,a,n,n][l],255*[n,n,o,s,s,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,s.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,s.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return A(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=A,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const s=i(75556),r=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,s,n]=e,[a,o,l]=t,u=i-a,c=s-o,d=n-l,h=(0,r.sqrt)(s**2+n**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,s.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,s,l]=e,u=(0,r.sqrt)(s**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=s*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let S=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);S+=2*(S<0?1:0)*Math.PI;const b=c-i,P=v-y;let M=y*v==0?0:S-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+S:(D=(w+S)/2,D-=(Math.abs(w-S)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*k/(0,r.sqrt)(20+k),F=1+.045*E,I=1+.015*E*x,A=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,r.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*A)*O;return(0,r.sqrt)(Math.pow(b/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const s=i(11944),r=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,s.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,s.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const s=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=s&&(0,r.gt0)(i)?new c(s,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const s=i(4866),r=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,r.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),s=(0,r.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const s=(0,u.ciede2000_delta_e)(e.lab,i.lab),r=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(s);return(0,n.clamp)(0,100,r)*o}(e,t)));return s/i}t.dominantColorCorrelation=function(e,t){return e=(0,r.compact)(e),t=(0,r.compact)(t),(0,r.isEmpty)(e)||(0,r.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,s.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),S=i(65976),b=i(53682),P=(0,s.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=b.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=b.ModeCount){const i=Date.now(),s=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,s=4*t;g=Math.round(Math.max(i,Math.min(s,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,s).map((e=>{const s=(0,p.kmeans)(f,g,{...T,seed:e}),r=x(s.centroids,f.length);if(r.lengtht&&k(g-1);const n=r.slice(0,t),o=function(e){const t=new m.Average;for(const[i,s]of a.entries()){const r=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=n&&(0,l.times)(s,(()=>t.push(n.value)))}return t.p84}(n);return{...s,centroids:n,description:{kIn:g,kOut:s.centroids.length,kMerged:r.length,score:o,iterations:s.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:s}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),A=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>S.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,S.dominantColorsToRgbHex)(A),pixelCount:f.length}),{dominantColors:A,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const s of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,s)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,s))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,s.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:s=3}){if(s<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:s,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*r,retries:s-1}))}function D(e,t){const i=e.countSum,s=e.size;k(e);const n=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>S.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:s,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[s,r]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(s),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:s}):(e.delete(s),e.incr(a.labhash,r))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const s=[];for(const t of e){const e=s.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?s.push(t):e.size+=t.size}const r=t/100;return(0,n.sortBy)(s.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const s=i(4866),r=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,s.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,s=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),s.push(e[2])}const r=(i.stdDev??0)+(s.stdDev??0),n=r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const s=i(75556),r=i(61570),n=i(84253);t.isModeData=function(e){return(0,s.gt0)(e.mode0)&&(0,s.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const s=i(75556),r=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,s.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,s.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const s=i(42748),r=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),s=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,s)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const s=i(889),r=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),s=i?.groups;return null==s?void 0:f.for((0,c.parseExifDateTime)(s.start,t),(0,c.parseExifDateTime)(s.end,t),(0,a.toInt)(s.index),(0,a.toInt)(s.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>s.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>s.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,s=1){if(null==e||!e.isValid||null==t||!t.isValid)return;s=(0,a.clamp)(1,1e3,(0,a.toInt)(s,{defaultValue:1})),i=(0,a.clamp)(0,s-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),n=(t.toMillis()-r)/(s+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,s)}constructor(e,t,i,s=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=s,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((s=>function({start:e,end:t,middle:i,field:s}){return null!=e[s]&&null!=t[s]?i[s]:void 0}({start:e,middle:t,end:i,field:s})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof s.ExifDate||e instanceof s.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof s.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof s.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof s.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),s=E(e);if(null!=i&&null!=s)return(0,c.gt0)(t)&&t>s-i?{start:Math.round((i+s)/2-t/2),end:Math.round((i+s)/2+t/2)}:{start:i,end:s}}function C(e,t,i,s){const[r,n]=(0,a.sortBy)([x(e,i),x(t,s)],(e=>e?.start));return null!=r&&null!=n&&null!=r&&null!=n&&(r.start===n.start||r.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof s.ExifDate?r.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:s}){if(null==e||null==t)return!1;if(i??(i=k(e)),s??(s=k(t)),C(e,t,i,s))return!0;const r=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==r&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,s)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const s=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,s.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const s=i(39938),r=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,s.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,s.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const s=i(42748),r=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=s.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const s=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&s.push(i+e.s)}return s.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const s=t.exec(e);if(null==s||(0,u.isEmptyObj)(s.groups))return;const{year:r,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(s.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(s.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(s);return b({year:r,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(s.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof s.ExifDate&&t instanceof s.ExifTime))return;const i=new s.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:s.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:s.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:s.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof s.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=s.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const s=i(42748),r=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=s.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=s.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=s.DateTime.DATETIME_MED){return(0,c.opt)(s.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const s=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,s.pad2)(e.getMonth()+1),(0,s.pad2)(e.getDate()),"-",(0,s.pad2)(e.getHours()),(0,s.pad2)(e.getMinutes()),(0,s.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,s.pad2)(e.getUTCMonth()+1),(0,s.pad2)(e.getUTCDate()),"-",(0,s.pad2)(e.getUTCHours()),(0,s.pad2)(e.getUTCMinutes()),(0,s.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(889),r=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function k(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(s=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:s,month:r,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",s=15*(0,c.round)(e/15),r=Math.abs(s),n=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${E(n)}:${E(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function A(e,t){const[i,s]=[e,t].map(g.datedToMillis);return null==i||null==s?void 0:i-s}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(A(e,t),l.dayMs)},t.diffMillis=A,t.closeTo=function(e,t,i){return(0,u.mapOr)(A(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,s=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(s+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const s={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,s):k(e)?.setZone(r,s)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const s=(0,T.getZoneName)(e);return null!=s&&"UTC"!==s||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),E=i(50140),D=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=A({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const s=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=s)return s;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function A({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:s=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const s=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${s})`,f:i=>I(i,s,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:s}))if(r(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=A;class O{constructor(e={}){s.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,s,"m",n).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,s,"m",n).call(this))),a(this,s,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=A({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,s=new WeakSet,r=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,s,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,s,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,s,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,s,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,s,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,s,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,s,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,s,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,s,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,s,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const s=i(66776),r=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,s.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,s.map)(o(e),(t=>{const i=l(e)??0;let s=(t+i/1e3).toString();for(t<10&&(s="0"+s),0===i&&(s+=".");s.length<6;)s+="0";return s}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const s=i(889),r=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof s.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const s=i(42748);t.isDateTime=function(e){return s.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const s=i(42748),r=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const s=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*s(),n=s(),a=s(),l=(0,o.toGt0)(s()),u=(0,o.toGt0)(s()),c=(0,o.toGt0)(s());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(s.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const s=i(4866),r=i(59694),n=i(75556),a=i(36218),o=(0,s.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const s=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(r=>{const n=s.format(new Date(2017,r));e.set(n,r+1),"short"===i&&"en-US"===t&&e.set(n+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const s=i(42748),r=i(4866),n=i(92507),a=i(43414);t.setupLuxon=(0,r.lazy)((async()=>{s.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>s.Settings.twoDigitCutoffYear=e)),s.Settings.defaultLocale=await(0,n.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const s=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=s&&Math.abs(s-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(s)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return S(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,s=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+s);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,A=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function O(e){return F(A().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=k(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof s.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof s.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function A(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function O(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||A(t,e))&&(!(0,u.gt0)(i)||O(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=A,t.validDay=O,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const s=i(889),r=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof s.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==s.UnsetZoneName&&e.zone.offset(Date.now())!==s.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===s.UnsetZoneName?void 0:e.zone?.name:e instanceof s.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const s=i(84253);t.AutoVacuumModes=(0,s.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const s=i(44726),r=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,r.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,s.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const s=i(4866),r=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,s.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,r.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const s=i(84253);t.CheckpointTypes=(0,s.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const s=i(4866),r=i(7162),n=i(61253),a=(0,s.lazy)((()=>(0,r.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const s of(0,n.sqliteFiles)(e)){const e=t.join(s.base).wip();i.push(e),await s.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const s=i(7162),r=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,s.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const s=Date.now();let a=0;const d=s+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const s=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+s+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(s)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const s=i(76387),r=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,s.isDated)(t)?[e,(0,r.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const s=i(4866),r=i(19658),n=i(43414);t.maxBatchPluckSize=(0,s.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(r.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const s=i(49411),r=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,r.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let r;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,s.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();r=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),S=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(S.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const s=Math.round(1.5*t);s>m.Settings.maxMemoryMb.valueOrDefault&&(S.warn("Large database: setting maxMemoryDb to "+s+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=s)}S.info("Opening "+e+"...");const b=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:r});S.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])S.tapThunk({msg:"PRAGMA "+e,result:()=>b.pragma(e)});const P=b;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const s=i(84253);t.RepairModes=(0,s.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const s=i(11944),r=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,r.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,s.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,s.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,s.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const s=i(95725),r=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...r.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...r.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,s.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const s=i(11944),r=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,r.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,s.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let r;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const s=i(4866),r=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,s.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),s=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:s.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,r.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:s.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,r.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(s).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const s=i(84253),r=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,s.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const s=i(84253);t.SynchronousModes=(0,s.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function x(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:b.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const s=i(4866),r=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,s.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const s=i(63410),r=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,s.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=s(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const s=i(39938),r=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,s.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const s=i(44470),r=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,s.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const s=i(70612),r=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,s.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const s=i(3955),r=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,s.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,r.cacheDir])if((0,s.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const s=i(39938),r=i(82798),n=i(3955),a=i(43414);function o(e){return(0,s.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const s=i(11944),r=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,s.uniq)([t,i,await S(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=s(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,s.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const s=i(38625),r=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,n.isPacked)()&&(0,s.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const s=i(38625),r=i(29405);t.doNotTrack=function(){return(0,s.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=s(i(87561)),n=i(49411),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const s of e)try{const e=(0,h.debom)(r.default.readFileSync(s)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,s]of(0,d.entries)(n))t.test(e)||(i[e]=s)}catch(e){console.warn("env(): failed to read .env file, "+s,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const s=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,s.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const s=i(84253);t.EnvKeys=(0,s.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const s=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,s.blank)(e))return i;let n;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:r}=n.groups;if((0,s.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=s(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const s=i(5712),r=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(b(e)),s=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),s-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new s.Rate,t.fatalErrorRate=new s.Rate,t.internalErrorRate=new s.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,s=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,s).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const s=i(11944),r=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,s.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const s=i(11944),r=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,s.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const s=i(4866),r=i(88491),n=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),S=i(6231),b=i(43414),P=(0,s.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*r.secondMs)).join((0,f.shortStringSha)(e.message,8,S.GeoRadix)+".json")}async eventsFrom(e=new Date,t=r.dayMs){const i=e.getTime(),s=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(s,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),s=await this.eventCount(),r=b.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:s>=r,meta:{event:M(e),recentEventCount:s,maxErrorsPerDay:r,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,s.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const s=i(11944),r=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,s.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const s=i(53525);class r extends Error{constructor(e){super(e+s.InternalErrorFlag)}}t.InternalError=r},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const s=i(39938),r=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,s.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const s=i(11944),r=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const s=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(s??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,s.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const s=t?.path;return(0,r.blank)(s)||(i=(0,h.dedupeNeedle)(i,s,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const s=i(4866),r=i(87489);function n(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,s.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],s.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,s,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,r,"f").get(e),clearTimeout),n(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,s,"f").get(e);return null!=a&&(a.resolve(t),n(this,s,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,r,"f").get(e),clearTimeout),n(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},s=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const s=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,s.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const s=i(71239),r=i(4866),n=i(80313);function a(e){const t=new s.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const s=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,s.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const s=i(39938),r=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,s.notBlank)(e.result)||(0,s.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),E=i(43383),D=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),A=i(75556),O=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Q=i(21142),Y=i(80294),Z=i(10408),X=i(53525),ee=i(30114),te=i(25015),ie=i(19653),se=i(95694),re=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,se.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),s=(0,me.isStoredEvent)(e)&&(0,Y.isRecentMs)(i,t.EventTimeoutMs);return s&&"exit"===e.name?(0,A.gt)(i,V.StartTs):s}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,A.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,s,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),s.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,s,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),s=(0,C.parseJSON)(e);null!=s&&i.push(s)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const n=Se((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,s,"m",f).call(this,e));r&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,A.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,s,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,s,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,O.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,s,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Z.errorToS)(e)+X.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Q.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),S.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,s,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Z.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+X.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+X.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const s=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){s.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const s=i(43947),r=i(79015);let n=!1;(0,s.later)((()=>(0,r.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},44982:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=s(i(87561)),n=s(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:s=!1,processUid:r,processGid:n}){if(null==e)return!1;const a=r??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(s&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const s=await(0,u.statMaybe)(i);if(null!=s){if(!s.isDirectory())return!1;if(t){if(!p(s,e))return!1}else if(t=!0,!m(s,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=s(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),s=await m(i.dir);for(const e of await(0,d.readdir_)(s))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(s,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const s=i(87561),r=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,s.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),E=i(88491),D=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),A=i(98510),O=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Q=i(91464),Y=i(2073),Z=i(69301),X=i(24586),ee=i(44982),te=i(77390),ie=i(51081),se=i(57400),re=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(s.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,s=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const s=Se().get(i);if(null!=s)return s;const r=(0,he.resolve)(i),n=new be(r,t);return Se().set(i,n),Se().set(r,n),n}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Q.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const s of t)!0===await e(s)&&i.push(s);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,s,"m",n).call(this)??await d(e=this.clearThisAndParent(),s,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const s of i)t.push(...(0,R.toA)(await s.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const s of i)if(s.isDirectory()){const i=await this._directoryEntryChild(s).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Z.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,X.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,s,"m",o).call(this,(0,Q.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,s,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,s,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const s=await e.sha();if(null!=s)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===s)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(s=>{const r=e.exec(s);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const s of e)for(const e of i)if((0,F.closeTo)(s,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const s=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(s,r)=>{try{const n=await e.f(s,(0,C.denull)(r));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{s.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const s=setInterval((async()=>{try{const s=await e.f();t(s)&&i.resolve(s)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||s.unref(),i.finally((()=>{clearInterval(s)}))}return i}}t.BaseFile=be,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Q.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*E.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const s=i(43414),r=i(17310),n=i(63526),a=i(3955);function o(e){return t=>s.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const s=i(11944),r=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,s.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const s=i(49411),r=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,s.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=s(i(49411)),n=s(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const s=i(1487),r=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,s.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,s){super("fs.DirWatcher("+e+")",(()=>this.close()),s),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:s}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(s,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},48640:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,S,b,P,M,_,T,E=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},D=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryIterator=t.Undone=t.Done=void 0;const k=i(49411),x=i(4866),C=i(11944),F=i(51367),I=i(75556),A=i(61570),O=i(8199),L=i(20636),R=i(17078),N=i(39784),B=i(13779),j=i(7162),z=i(91464),V=i(10408),W=i(25015),U=i(43414),q=i(78362),H=i(32421),G=i(35280),$=i(67220),J=i(64067),K=i(3955),Q=i(23872),Y=i(24948);t.Done={done:!0},t.Undone={done:!1};class Z{constructor(e,i,r){s.add(this),this.dir=e,this.ctx=i,this.parent=r,this.start=Date.now(),n.set(this,void 0),a.set(this,[]),o.set(this,[]),l.set(this,[]),u.set(this,[]),c.set(this,void 0),d.set(this,!1),h.set(this,0),f.set(this,0),m.set(this,0),p.set(this,0),g.set(this,0),this.rootDir=(0,x.lazy)((()=>this.parent?.rootDir()??this.dir)),this.pathFromRoot=(0,x.lazy)((()=>(0,K.posixPathFrom)({nativePath:this.rootDir().dir},this.dir))),this.nextTimeout=(0,x.lazy)((()=>U.Settings.statTimeoutMs.valueOrDefault+(0,I.clamp)(0,512,10*(512-this.depth())))),v.set(this,(0,x.lazy)((async()=>{const e=await(0,J.whyExcludedDirectory)(this.dir)??(!this.isRoot&&await(0,H.isPosixMountpoint)(this.dir)?"nested mountpoint":void 0);if(null!=e)return D(this,n,"f").info("skipping ignorable dir, "+this.dir,{details:e}),this.cancel({state:Y.SyncDirStates.skipped,details:e}),t.Done}))),b.set(this,(0,x.lazy)((async()=>{const[e,t]=(0,B.partition)((0,N.toA)(await this.dir.children()),(e=>D(this,s,"m",S).call(this,e)));for(const t of e)(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.skipped,details:"this was scanned in a prior incomplete sync"});D(this,u,"f").push(...t.filter((e=>e.isDirectory()))),E(this,p,D(this,u,"f").length,"f");const i=t.filter((e=>e.isFile())),[r,n]=(0,B.partition)(i,W.isSidecarExt);D(this,a,"f").push(...n),D(this,l,"f").push(...r),E(this,f,D(this,a,"f").length,"f")}))),(0,Y.syncReport)().onProgress({path:e.nativePath+k.sep,from:"DirectoryIterator",state:Y.SyncDirStates.scanning}),this.name="dir.DirectoryIterator("+e+")",E(this,n,(0,j.mkLogger)(this.name),"f")}get isRoot(){return null==this.parent}isDone(){return D(this,d,"f")}status(){return{root:this.rootDir().nativePath,path:this.pathFromRoot(),isDone:this.isDone()}}cancel(e){return D(this,d,"f")||(E(this,d,!0,"f"),(0,Y.syncReport)().onProgress({path:this.dir.nativePath+k.sep,from:"DirectoryIterator",state:Y.SyncDirStates.canceled,...e,elapsedMs:Date.now()-this.start})),t.Done}depth(){return(0,z.countChars)(this.dir.nativePath,k.sep)}async next(e){var i;try{D(this,n,"f").trace("next() starting",{runMs:e-Date.now()});const r=await(0,L.thenOrTimeout)(D(this,s,"m",y).call(this,e),this.nextTimeout());return D(this,n,"f").trace("next() finished",{result:r}),r===L.Timeout?(E(this,g,(i=D(this,g,"f"),++i),"f"),D(this,n,"f").warn(".next() timed out",{statTimeoutMs:U.Settings.statTimeoutMs.valueOrDefault,timeoutCount:D(this,g,"f")}),D(this,g,"f")>3?(D(this,n,"f").warn(".next(): too many timeouts, giving up on this directory."),this.cancel({state:Y.SyncDirStates.timeout,details:"Failed to scan, even after 3 retries"})):t.Undone):(E(this,g,0,"f"),r)}catch(e){return D(this,n,"f").warn("next() failed",{error:e}),this.cancel({state:Y.SyncDirStates.failed,details:"Error thrown during scan: "+(0,V.errorToS)(e)})}}}t.DirectoryIterator=Z,r=Z,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,g=new WeakMap,v=new WeakMap,b=new WeakMap,s=new WeakSet,y=async function(e){return(D(this,d,"f")?t.Done:void 0)??await D(this,v,"f").call(this)??await D(this,b,"f").call(this)??await D(this,s,"m",P).call(this,e)??await D(this,s,"m",M).call(this,e)??await D(this,s,"m",_).call(this,e)??await D(this,s,"m",T).call(this)},w=function(e){return this.ctx.ended?this.cancel({details:"DirectoryWalker was ended"}):D(this,d,"f")?t.Done:(0,$.isPaused)()||Date.now()>e?t.Undone:void 0},S=function(e){return D(this,n,"f").tap({msg:"shouldSkipChild()",result:(0,C.isNotEmpty)(this.ctx.startAtNativePath)&&(0,O.cmpArr)((0,K.splitNativePath)(e.nativePath),this.ctx.startAtNativePath,!1)<=0,meta:{child:e.base}})},P=async function(e){var t;const i=[];let r;for(;null==r&&(0,C.isNotEmpty)(D(this,a,"f"));){const o=D(this,a,"f").shift();E(this,h,(t=D(this,h,"f"),++t),"f");const l=await(0,Q.whyRejectFileSimple)(o);null!=l?(D(this,n,"f").debug("maybePopChildFile()",{child:o,whyReject:l}),(0,Y.syncReport)().onProgress({path:o.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.rejected,details:l})):i.push(o),r??(r=D(this,s,"m",w).call(this,e)),null!=r&&D(this,n,"f").trace("maybePopChildFile() timeout",{timeout:r})}return(0,C.isNotEmpty)(i)&&(D(this,n,"f").trace("maybePopChildFile()",{toAdd:i}),await this.ctx.fileHandler(i),D(this,o,"f").push(...i)),r},M=async function(e){for(;(0,C.isNotEmpty)(D(this,l,"f"));){const t=D(this,l,"f").shift();if(U.Settings.tagAlbumFilenames.values.includes(t.base))(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.note,details:"sidecar will be checked for for album metadata"});else{const e=D(this,o,"f").filter((e=>(0,q.isSidecarOf)(e,t)));(0,C.isNotEmpty)(e)?(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.note,details:"sidecar will be processed with "+(0,F.andList)(e.map((e=>e.base.normalize())))}):(0,Y.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:Y.SyncFileStates.rejected,details:"sidecar will be ignored (no importable file was found to be relevant to this sidecar's name)"})}const i=D(this,s,"m",w).call(this,e);if(null!=i)return D(this,n,"f").trace("handleSidecars() timeout",{timeout:i}),i}},_=async function(e){var t;let i;for(;null==i&&(null!=D(this,c,"f")||(0,C.isNotEmpty)(D(this,u,"f")));){if(null==D(this,c,"f")){const e=D(this,u,"f").shift();null==e||(D(this,n,"f").trace("delegating to child dir, "+e),E(this,m,(t=D(this,m,"f"),++t),"f"),E(this,c,new r(e,this.ctx,this),"f"))}if(null!=D(this,c,"f")){const t=await D(this,c,"f").next(e);(t?.done??!0===D(this,c,"f")?.isDone())&&E(this,c,void 0,"f")}i=D(this,s,"m",w).call(this,e)}return i},T=async function(){if((0,C.isNotEmpty)(D(this,a,"f"))||(0,C.isNotEmpty)(D(this,u,"f"))||null!=D(this,c,"f"))return D(this,n,"f").error("maybeCompleteResult: not done (?!)",(0,A.pick)(this,"result","pendingChildren","childDelegate","pendingChildDirs")),t.Undone;if(!D(this,d,"f")){E(this,d,!0,"f");const e=await(0,G.mkFolderUrl)(this.dir.nativePath),t=e?.with({query:null}),i=t?.toString();(0,Y.syncReport)().onProgress({path:this.dir.nativePath+k.sep,state:Y.SyncDirStates.scanned,from:"DirectoryIterator",details:`${D(this,h,"f")}/${(0,R.plur)(D(this,f,"f"),"file")} and ${D(this,m,"f")}/${(0,R.plur)(D(this,p,"f"),"directory","directories")}`,url:i,elapsedMs:Date.now()-this.start}),await this.ctx.directoryListener(this.dir)}return t.Done}},97463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryWalker=void 0;const s=i(4866),r=i(88491),n=i(75556),a=i(19658),o=i(28807),l=i(91641),u=i(17354),c=i(43414),d=i(76052),h=i(48640),f=i(3955);class m extends o.EndableInterval{constructor(e,t,i,s,r){super({name:"dir.DirectoryWalker("+e.nativePath+")",callback:()=>this.runChunk(),intervalMs:m.IntervalMs(),rank:l.EndableRanks.first}),this.root=e,this.fileHandler=t,this.directoryListener=i,this.highPriority=!0,this.runChunk=(0,u.oneAtATime)({runLaterIfBusy:!1,fn:async()=>{if(!a.isTest&&(0,d.doNotRun)(this))return;const e=await this.iterator.next(Date.now()+this.runMs);this.logger.debug("runSlice()",{result:e}),!0===e?.done&&(this.logger.info("runSlice(): completed iteration"),this.end())}}),this.runMs=r??(0,n.clamp)(1,100,c.Settings.cpuBusyPercent.valueOrDefault)/100*m.IntervalMs(),null!=s&&((0,f.containedByNativePath)({ancestor:this.root.nativePath,descendant:s})?this.startAtNativePath=(0,f.splitNativePath)(s):this.logger.error("bad startAtNativePath: ignoring.",{root:this.root.nativePath,startAtNativePath:s})),this.iterator=new h.DirectoryIterator(e,this),this.runChunk()}}t.DirectoryWalker=m,m.IntervalMs=(0,s.lazy)((()=>2*r.secondMs))},93033:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=s(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},s=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(s.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(s.dir,`${s.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${s.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},s=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(s.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(s.dir,`${s.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${s.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),S=i(2023),b=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),E=i(20902),D=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),A=i(98462),O=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const s=(0,B.isSimpleFile)(e)?e:A.BaseFile.for(e),r=V.test(t)||s.isDirectorySync(),n=(0,R.native2posix)(s.nativePath),a=r?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(s.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(s.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,S.pairToObject)(this.reason,a(this,s,"m",r).bind(this)):{}}}s=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,s){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new U(`**/${t}/${r[0]}/`,s)),r.length>1&&e.push(new U(`**/${t}/(${r.join("|")})/`,s))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const s=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",s,"Linux /var"),t("mnt",s,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Q=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:se,notInHiddenPhotoStructureDir:ae,notNoMedia:re,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Q();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const s=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,n]=(0,g.partition)(s,(e=>e.pattern.endsWith("/")));return{dir:r,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function X(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...X(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function se(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,b.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,b.thenNot)((0,O.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=X,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),s.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,s,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,s=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),S=i(77696),b=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){s.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,r.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,s,"m",a).call(this)}),o(this,r,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,r=new WeakMap,s=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,r,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await l(this,s,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,r,"f").warn("cleanup(): ENOENT "+e,t),(0,b.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,r,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,r,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,r,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,r,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const s=i(87561),r=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof s.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const s=i(93977),r=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,s.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const s=i(53221),r=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,s.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,n.blank)(r)||(0,n.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const s=i(66776),r=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,s.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:s,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:s})));try{for(const t of u)if(!0!==await(0,r.thenOrTimeout)(t.acquire_(),s))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),T=i(11944),E=i(37609),D=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),A=i(20636),O=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",n)+1),"f",n),(0,T.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",n)),N.serviceName.prior(),(0,O.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,O.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),s.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,s,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,s,"m",f).call(this,e)??w(this,s,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);S(this,c,setInterval((()=>w(this,s,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,s,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,s,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,A.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,s=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,s,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,s,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,s,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,s,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const s=i(39938),r=i(44726),n=i(82798),a=i(95725);function o(e){return(0,s.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,s.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,s.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),E=i(79015),D=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),A=i(95725),O=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const s=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,s),s.on("close",(()=>{this.path2watcher.delete(e)})),s.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,A.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),s.add(this),this.args=e,this.id=(0,F.uid)(),r.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,s,"m",o).call(this),!0===e?.isFile()&&await c(this,s,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,O.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,S.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,s,"m",o).call(this):!a&&!!i.isFile()&&await c(this,s,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,r,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,A.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const s=i(39938),r=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,s.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let s=e;for(const e of i.aggressive?d:c){const t=s.match(e);if((0,n.gt0)(t?.index)){const e=s.slice(0,t.index).trim();e.length>0&&(s=e)}}return e===s?e:f(s,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,s.blank)(i))return e;const r=(0,u.parsePosixPath)(i),n=h(r,{aggressive:!1});return[...t,n+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),s=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(s),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const r=s(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const s=(0,o.toS)(e).match(this.pattern);null!=s&&this.push(s[1]??s[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([r.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=s(i(44470)),n=s(i(87561)),a=i(76402),o=s(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=s(i(6005)),n=s(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const s=(0,y.toNativePath_)(e);if(i){const t=S().get(s);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:s,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:s,prior:t}),S().delete(s)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const s=r.default.createHash(i);return await(0,a.pipeline)([e,...t,s]),s.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const s=i(4866),r=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,s.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const s=i(39938),r=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,s.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const s=i(4866),r=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,s.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,r.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const s=i(84492),r=i(44726),n=i(82798);class a extends s.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const s=(this._prior+(0,n.toS)(e)).split((0,r.newlineRe)()),a=s.pop();this._prior=a??"";let o=!1;for(const e of s)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=s(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const s=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),s=(0,r.toNativePath_)(t);return null!=i&&null!=s&&i===s}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,s.actualPath_)((0,r.toNativePath_)(e))===await(0,s.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const s=await Promise.race([T(e,t),D(e,t)]);return t.halt(),s}(t.nativePath)))}async function T(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const s of t){if(!0===i?.halted)return null;if(P(s.basename))return y().tap({msg:e+" has a noMedia child, "+s.basename,result:!0});if(s.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,s.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=s(i(44470)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",s=n.default.parse(t?.path??e);return{...s,ext:(s.ext??"")+i,base:(s.base??"")+i}}function E(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const s=e.acceptSelf??!1;return t===i?s:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const s=e(t),r=e(i);return null!=s&&null!=r&&(g.isLinux?s===r:(0,m.equalsIgnoreCase)(s,r))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=E,t.grandParentBasename=function(e){return E(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),s=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(s))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===s?"":(0,m.stripPrefix)((0,y.native2posix)(s).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const s=x(e),r=[],n=[s.pop()];for(;s.length>0;)if(r.length=t){s.unshift(r.pop());break}}else if(n.unshift(s.pop()),F([...r,...n]).length>=t){s.push(n.shift());break}return s.length>0&&r.push("โ€ฆ"),F([...r,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=s(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const s=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of s){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:s})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var s,r,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),E=i(61570),D=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),A=i(14889),O=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Q=i(19209),Y=i(25116),Z=i(32421),X=i(53719),ee=i(46573),te=i(98462),ie=i(21084),se=i(25015),re=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),s.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Q.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:A.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),s=new pe(i,t);return(0,O.isString)(e)&&me().set(e,s),me().set(i,s),s}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Q.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,s=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(s)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,se.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,se.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,se.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:s=!1,timeoutMs:r,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async s=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(s),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&s?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,O.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,O.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:s=!1,timeoutMs:r,dirty:n=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:s,timeoutMs:r,dirty:n},(async()=>{const s=this.wip();try{await s.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(s),r);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>s.clear().isNonEmptyFile(i)),{timeoutMs:A.ShortCommandTimeoutMs,intervalMs:250}))return await s.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(A.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await s.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,s,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,s,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,X.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(A.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*X.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,s=new WeakSet,r=async function(e){let t,i=e;const s=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await s.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,s.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>s.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(r.size,await s.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await s.size({refresh:!0})});await this.maybeVerifySameOrThrow_(s),i=e.eql(s)?e:await s.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${s?.nativePath}) failed: ${t}`),await s.unlink(),s.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const s=await this.stat_(),r=s?.size;return null==s||null==r?this.pflog().throw("Can't copy missing files"):(r>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const s=i(11944),r=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),S=i(64067),b=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,b.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function A(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,S.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function O(e){return[...A(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,S.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,s.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=A,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...A(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...A(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,S.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...A(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=s(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,n.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",s=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(s[0],t)&&s.unshift(),i+s.join(r.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=s(i(49411)),n=s(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const s=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(s,e))return s}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const s=i(44470),r=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,s.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const s=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const r=i??(await(0,s.stat)(e)).size-t,a=Buffer.alloc(r);return n=await(0,s.open)(e,"r"),await(0,s.read)(n,a,0,r,t)}finally{(0,r.mapGte0)(n,s.close)}}},41544:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const s=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,s.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const s=i(84492);class r extends s.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=s(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),s=E(e),r=await(0,h.thenOrTimeout)(s,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):E(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=s(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const s=i(94383),r=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new s.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const s=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,s.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=s(i(87561)),n=s(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),s=b(t);if(i!==s)return"inconsistent file type: "+i+" โ‰  "+s;for(const i of["size","mtime"]){const s=e[i],r=t[i],n=(0,u.diff)(P(s),P(r));if(null==n||n>1)return"unmatched "+i+": "+s+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=s(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const s=i(43414);t.statTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const s=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const s=new n(t,i,!0);return s.read(e),s.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,s.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,s.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=s(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,s)=>{!1===e.write(t,(e=>{e&&s(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),S=i(21669),b=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),E=i(91641),D=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),A=i(18849),O=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,s,r,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=s,this.from=r,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,O.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),s.add(this),r.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,r,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,A.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const s=Date.now(),r={ts:s,at:new Date(s).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,b.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([r],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:s}){const r=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await s(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-r,...n,state:a}),n}catch(s){throw this.logger.warn("wrap_() caught error",{error:s,stack:s.stack}),this.onProgress({path:e,from:i,state:s instanceof S.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(s),elapsedMs:Date.now()-r}),s}}get output(){return l(this,n,"f")??l(this,s,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,r,"f")}}t.SyncReport=$,r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=function(){return u(this,r,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,r,"f").nativePath),this.logger.info("Opening new report: "+l(this,r,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,r,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,r,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},59220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unprocessedPaths_=t.readSyncReport_=void 0;const s=i(87561),r=i(84492),n=i(76402),a=i(57153),o=i(39938),l=i(91464),u=i(51081),c=i(13348),d=i(95725),h=i(24948),f={header:!0,skipEmptyLines:"greedy"};t.readSyncReport_=async function(e){const t=(await(0,c.readLines_)(e)).join(u.Newline);return(0,a.parse)(t,f)};class m extends r.Transform{constructor(e=new Set,t=new Set,i,s){super({objectMode:!0}),this.enqueued=e,this.settled=t,this.accept=i,this.fileDoneStates=s}_write(e,t,i){if(null!=e&&h.SyncFileStates.includes(e.state)&&(0,o.notBlank)(e.path)&&this.accept(e.path)){const t=e;"enqueued"===t.state?this.enqueued.add(t.path):this.fileDoneStates.has(t.state)&&this.settled.add(t.path)}i()}}t.unprocessedPaths_=async function({syncReportJsons:e,acceptPath:t=(()=>!0),fileDoneStates:i=h.FileDoneStates}){const r=new Set,o=new Set;for(const l of e)await(0,n.pipeline)((0,s.createReadStream)((0,d.toNativePath_)(l)),(0,a.parse)(a.NODE_STREAM_INPUT,f),new m(r,o,t,i));const u=[...r].filter((e=>!o.has(e)));return(0,l.sortIgnoreCase)(u)}},22143:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=s(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=s(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const s=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(s,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(r.default.ensureFile(s),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const s=i(4866),r=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,s.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,s.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,s.lazy)(g),t.libraryUidStore=g,(0,r.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(s){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:s})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=s(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const s=i(39938),r=i(14889),n=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,s.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const s=i(84492),r=i(34996);class n extends s.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=s(i(44470)),n=s(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=s(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const s=[],n=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>s.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>s.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>s.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(s))throw new f.WrappedError("zPipe("+e+") failed",{causes:s,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},44606:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=s(i(52167)),n=i(43383),a=i(43947),o=i(77125),l=i(7162),u=i(55568),c=i(14889),d=i(20681),h=i(43414),f=i(19209),m=i(36297),p=i(79403),g=(0,n.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({later:async()=>{try{if(!(0,u.isWebService)()){const e=f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}).toString(),t=await r.default.get(e,{timeout:c.ShortCommandTimeoutMs}),{status:i,data:s}=t;if(m.HttpStatusIs.ok(i)&&(0,o.isHealthCheckSummary)(s))return s.libraryDir!==(h.Settings.libraryDir.valueOrDefault??null)?void g().error("getHealthSummary(): libraryDir mismatch",{local:h.Settings.libraryDir.valueOrDefault,remote:s.libraryDir}):(g().debug("getHealthSummary()",{url:e,status:i,data:s}),s);g().warn("getHealthSummary(): invalid response",{url:e,status:i,data:s})}}catch(e){g().warn("Failed to get health check summary from web service",{error:e})}},ttlMs:c.ShortCommandTimeoutMs}),t.getLocalHealthSummary=(0,d.lazyAsync)({later:()=>p.HealthCheck.awaitSettled(),ttlMs:c.ShortCommandTimeoutMs}),(0,a.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const s=i(53719),r=i(79403),n=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...r.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:r.HealthCheck.lastErrors(),timeoutMs:(0,s.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const S=i(4866),b=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),E=i(66776),D=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),A=i(13779),O=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Q=i(62905),Y=i(18295),Z=(0,S.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class X{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,r,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,r,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,r,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,r,"f",l).toA()}static addLoadingMsg(e){v(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,b.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Z().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,r,"f",h).entriesByCountDesc()}),(0,E.map)((0,A.leastBy)(e,(e=>[v(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,r,"f",h).incr(e.msg))),Z().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return v(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=r.summary();if(t.settledCountv(r,r,"f",a).enqueue({name:this.id,l:()=>v(this,s,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>r.onResultChange(),onError:()=>r.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,s,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,b.isEmpty)(e))return{};const[t,i]=(0,A.partition)(e,(e=>"button"===e.type||"POST"===e.method)),s={};return(0,b.isNotEmpty)(i)&&(s.links=(0,b.uniqBy)(i)),(0,b.isNotEmpty)(t)&&(s.buttons=(0,b.uniqBy)(t)),s}t.HealthCheck=X,r=X,s=new WeakSet,o=function(){return(0,b.filterInPlace)(v(this,r,"f",n),(e=>!e.isPending)),v(this,r,"f",n)},m=function(e){const t=Z().tap({level:"info",msg:"#summary()",result:(0,Y.summarizeHealthChecksSync)({errors:v(this,r,"f",l),skipPending:v(this,r,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,r,!0,"f",u),t.state!==v(this,r,"f",c).last?.state&&v(this,r,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Z().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,s,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,s,"m",g).call(this,i)}catch(e){return v(this,s,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=r.normalizeMsg(e.msg),s=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,b.compact)([...e?.links??("ok"===s||"pending"===s?this.okLinks:"warn"===s?this.warnLinks:"no-library"===s?this.noLibraryLinks:"error"===s?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:s,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Q.HealthCheckLevelToLogLevel[s],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,s,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new O.BoundedList(10)},u={value:!1},c={value:new O.BoundedList(10)},d={value:new O.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},X.all=(0,S.lazy)((()=>Object.freeze((0,P.sortBy)(v(r,r,"f",f),(e=>e.sortBy))))),X.summary=(0,S.lazy)((()=>v(r,r,"m",m).call(r))),X.resetDebounced=(0,N.debounce)((()=>r.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const s=i(84253);t.HealthCheckIds=(0,s.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const s=i(36535),r=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,s.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const s=i(11944),r=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,s.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=s(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:s}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(s,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const s=i(11944),r=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:s}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),s))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,s.uniq)((0,s.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,s.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,s.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const s=i(47261),r=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),S=i(21084),b=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),E=i(43414),D=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),A=i(14489),O=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,r.lazy)((()=>new S.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[s.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const s=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==s){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(s);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:s,whyRejected:e})}const r=i.sha??await s.sha();if(null!=r)if(!0!==await(0,t.isBadSha)(r))try{return await this._build(s,i)}catch(t){e.push(t),L().set(r,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",s);else this.logger.info("skipping: cannot read SHA",s),e.push(new Error("Cannot read "+s.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,O.throwIfInvalidFile_)(e);const i=await e.size(),s=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:s,best:t.uri}),null==i||null==s)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:a,height:o,sha:l,mimetype:u}=t;if(null==r||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:s,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const s=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(s,r)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(s,r);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),s=await this.priorIfValid_(t,i);if(null!=s)return s;const r=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),S=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,b=(0,d.pick)(t,"width","height");{let e=o.clone(),t=b;for(const[i,s]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(s.reducer.name,i.width).wip();e=s.resize(i,e),t=i,s.name===S&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&s.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await s.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+s.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:b,bestFitNameForSq:S}),g=o,p=b):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:S});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),s=p,n=t.outputSize(p??b);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),r.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(s)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const s=i(13783),r=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,s){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(s)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),s=(0,o.toInt)(i[0]),r=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(s)?{file:t,assetId:s,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:s,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,s.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){s.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,s,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",s=t?.[i];if(!(0,o.isEmpty)(s))return s;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},s=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const s=i(84253);t.CropStrategies=(0,s.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=s(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;ir?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const s=i(11944),r=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,s.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,s=Math.round(Math.sqrt(t*i));return{width:s,height:Math.round(s/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const s=u(e,i);return null==s?[]:a.Rotations.filter((e=>u(c(t,e),i)===s))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const s=i(4866),r=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,s.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const s=i(11944),r=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),s=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,s.push([a,n])))}return s},t.equivalentFitSizes=function(e,t){return(0,s.includesAll)((0,s.compactBlanks)(e).map(l),(0,s.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const s=i(39938),r=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,s.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,s.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,s.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,s.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,s.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const s=i(4866),r=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,s.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,s.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const s=i(39938),r=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,s.blank)(e)&&n.test((0,r.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const s=i(93977),r=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,s){const r=await(0,t.imageCacheDir_)();i??(i=e.name),s=(0,c.ensurePrefix)(s??e.ext,".");const n=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+s);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:s,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,s.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),s=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await s.parent().mkdirp_(),s},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:s}){return(await P(e,t,i)).applyIfEmpty_({fn_:s,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,s){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:s,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(s){return S().throw("withImgCache_() failed",{error:s,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=s(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),S=i(95725),b=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),E=i(68107),D=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,b.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,S.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function A(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const s=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:s});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const s=(0,b.mkLogger)("ImageHash("+e+")");if(null==t)return s.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:A}),t._imageHash_=A,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),S=i(60346),b=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),E=i(72461),D=i(36143),k=(0,s.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,r.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,r.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),s=Math.max(e.length,t.length,i);return(s-i)/s};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const s=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),r=i*i;for(;s.length%r!=0;)s.unshift(0);return s.length===r||t?s.slice(0,r):s.slice(0,r).map(((e,t)=>4*e+2*s[t+r]+s[t+2*r]))}function I({a:e,b:t,greyscale:i,dim:s=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,s),l=F(t,i,s);(0,r.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,b.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function A(e,t,i="debug",s={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),s)})}function O(e,t,i={}){const s=(0,E.toImageHash)(e),r=(0,E.toImageHash)(t);if(null==s||null==r)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(s.isGreyscale??C(s.meanHash))||(r.isGreyscale??C(r.meanHash))),f=I({a:s.meanHash,b:r.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(s,r)}),m=I({a:s.diffHash,b:r.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:s.dctHash,b:r.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(s.dominantColors,r.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=s.mimetype===r.mimetype,v=(0,T.aspectRatio)(s),b=(0,T.aspectRatio)((0,o.maybeDimSwap)(r,f.bRotation)),P=null!=v&&null!=b&&!(0,o.isCloseAspectRatio)(v,b);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),A=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(v)} vs ${(0,D.fmtAspectRatio)(b)})`);const L=[],N=new S.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=A,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:A,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:b,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(s,"uri","id","assetId"),b:(0,d.pickCompact)(r,"uri","id","assetId"),...V}),{a:s,b:r,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const s=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",r=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,b.rotateSquareMatrix)(r,e).map((e=>e.toString(2))).join("")+s))))},t.hammRatio=I,t.isSimilarImage=A,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",s={}){return A(e,t,i,{rotationsToCheck:[0],...s,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,s,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,s,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,s,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(s,s,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,s=m,r={value:[]},m.UHD8k=new s("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new s("uhd5k",5120,2880,h.Fit,!1),m.UHD=new s("uhd4k",4096,2160,h.Fit),m.QHD=new s("qhd",3120,1440,h.Fit),m.FHD=new s("fhd",1920,1080,h.Fit),m.HD=new s("hd",1280,720,h.Fit),m.WVGA=new s("wvga",720,480,h.Fit),m.QVGA=new s("qvga",320,240,h.Fit),m.QQVGA=new s("qqvga",160,120,h.Fit),m.S480=new s("s480",480,480,h.Square),m.S240=new s("s240",240,240,h.Square),m.S120=new s("s120",120,120,h.Square),m.S60=new s("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const s=i(4866),r=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),s=i?.capturedAt;null!=s&&(delete i.capturedAt,(0,n.assignFields)(i,s.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=s(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,s)=>t>=(0===s?e[i]:s%i==0?e[s-i]:e[s-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),s=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(s.map(c)),diffHash:(0,n.flatten)(s.map(d))}}},35254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const s=i(4866),r=i(18941),n=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,s.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const s=i(4866),r=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,s.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const s=i(11944),r=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const s=Math.abs(e-t);return s>i?void 0:s}))??e))}function c(e,i,s=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),s)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const s=Math.abs(t.i-e);return s[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const s=i(4866),r=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,s.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,s.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,s,n,a]=e.split("\t"),o=(0,r.toGt0)(n),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:s,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const s=i(4866),r=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,s.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,s){const r=(0,d.lteBoth)(e,s)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(s,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=s(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const s=i(84253);t.SharpFailOns=(0,s.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(889),n=s(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),S=i(79141),b=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),E=i(84685),D=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),A=i(49312),O=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,s,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const s=B().addParameterContext(e.nativePath);j();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return s.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void s.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),b=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return s.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:b,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),O=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||O||L||z)s.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:O,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)s.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof r.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){s.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),b&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new S.WrappedError("Failed to extract video frame for "+e,t)}else s.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return s.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...r};s.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){s.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new S.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const s=i(43649),r=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=r.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*r.secondMs},p1:{x:20*o.MB,y:12*r.secondMs}},p={p0:{x:11*o.MB,y:12*r.secondMs},p1:{x:26*o.MB,y:24*r.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,r=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,s.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+r+n+c+d),dbMs:i,tagMs:r,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,s.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=s(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),S=i(23024),b=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),s=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(s)&&_().throw(s,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,b.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,S.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const s=i(4866),r=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,s.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,s.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const s=i(4866),r=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),E=i(49586),D=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),A=i(68107),O=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,s.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const s=j("extractMaxBitrate",e),r=D.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,r))return s.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return s.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return s.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,s.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,s.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),s=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,R.cachedImageFile_)(s,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await s.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(s,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,L.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:s,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,O.commandTimeoutMs)()}),r.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const s=i.MIMEType;if(!(0,F.isVideoMimeType)(s))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:s}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,s);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:s,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const s=j("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,n.isTrue)(i?.force))return s.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void s.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return s.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return s.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),s=await(0,C.readRawTags)(e),r=(0,x.extractDurationSec)(s),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,n,1.5),meta:{srcDurationSec:r,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return s.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,r={src:e,...V(e,d)},n=J(o,r.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?s.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),s.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{s.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(r));0!==o.code&&s.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const s=i(11944),r=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),s=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+s),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,s.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,s.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...A(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const s=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(s))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const s=i(75556),r=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,s.toGt0)(n.Settings.ffmpegThreads.value)??(0,s.clamp)(1,6,(0,s.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const s=i(4866),r=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,s.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const s=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(s,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),S=i(7218),b=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,s.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,b.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),s=await(0,S.dimensions)(e);if(null==s)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(s),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(s)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),b=[...E,...D,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:b,opts:F});const I=(0,d.execFile)(w,b,C,F),A=[];function O(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const s=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});A.push(s)}}I.on("error",O),I.stderr.on("data",O);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,r.isNotEmpty)(A))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:A,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const s=i(4866),r=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,s.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},87308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.r=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(43383),l=i(87748),u=i(66776),c=i(8199),d=i(7162),h=i(29731),f=i(42041),m=i(4586),p=i(98250),g=i(10309),y=i(43414),v=i(53719),w=i(10508),S=i(69060),b=i(13700),P=i(59714),M=(0,o.defer)((()=>(0,d.mkLogger)(_().l))),_=(0,s.rolazy)((()=>(0,w.j)("G8oAKIzTFfOihHWPgG6m/h0h65IqCWu72UHSOixdfW12GgbIbSdJW2sLEmvLsqcHfOPXk00SqojDRomicXUE+MuLfPaoTzFWZPq8AdmWyQVUWERkBLoYBhqafaAvY27+LDra0blcQ4Vnjn/ukQh/C4o0cd0B")));async function T(e){const t=await(0,b.sids)({timeoutMs:(0,v.commandTimeoutMs)()});if((0,r.isEmpty)(t))return M().warn("no-op: empty sids");const i=(0,l.stringify)({uids:[...t,e],coupon:y.Settings.coupon.valueOrDefault,version:f.version}),s={..._().r,body:i},n=await(0,g.request)(_().u,s);M().info(_().u,{req:s,response:n}),n.ok?await(0,P.writeLicense)(JSON.parse(n.body)?.[_().a],(0,v.commandTimeoutMs)()):M().warn(_().u,{req:s,response:n})}t.r=(0,s.rolazy)((async()=>{const e=_().s+": ";try{if(!y.Settings[_().s].valueOrDefault)return M().debug(e+"no-op (settings disabled)");const t=(await(0,S.m)()).filter((e=>null!=e.l&&(0,n.notBlank)(e.s))),i=new Date,s=t.find((e=>e.ok&&(0,c.gt)(i,e.l?.exp)));if(null!=s)return M().debug(e+"no-op: ",s);const r=await(0,u.map)((0,m.configDir)(),(e=>p.PosixFile.for(e).join(_().s+"-v"+f.versionMajor+"."+f.versionMinor).mkdirp_()));for(const s of t){if((0,n.blank)(s.s)||null==s.l||ie.startsWith("cu:")));if(null!=t){if(await(r?.join((0,h.shortFsStringSha)(s.s,14)+".txt").applyIfEmpty_({fn_:async i=>{await T(t),await i.writeJson_({l:s.l,at:Date.now()}),M().warn(e+"requested",s)},timeoutMs:(0,v.commandTimeoutMs)()})),await(0,S.p)())break}else M().debug(e+"skipping (no cu)",s)}}catch(t){M().warn(e+"failed",t)}}),15*a.minuteMs)},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const s=i(65628);t.j=function(e){return JSON.parse((0,s.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const s=i(39938),r=i(43414),n=i(69060);t.getEmail=async function(){const e=r.Settings.email.value;if((0,s.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,s.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const s=i(35666),r=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,s){this.s=e,this._l=t,this._sids=i,this.meta={src:s}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,r.uniq)(e.map(c.getScheme)),i=(0,r.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),s=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=s,this.meta[(0,u.k)().m]=i,a&&s}cmpVal(){return[this.ok,-(s.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const s=i(4866),r=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),S=i(80294),b=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),E=i(43414),D=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,s.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function A(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),s=(0,S.utcIsoToTs)(i[(0,t.k)().i]);if(null==s)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const r=(0,S.utcIsoToTs)(i[(0,t.k)().r]);if(null==r)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(s),i[(0,t.k)().r]=new Date(r),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function O(e,i,s,r){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await A(e),sids:null!=r?r:await(0,C.sids)({timeoutMs:s}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],s=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of s.reverse()){const s=await O((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=s&&i.push(s)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=A,t.v=O,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const s=await O(e,t,i);return(0,a.isTrue)(s?.ok)&&s instanceof k.L?s:void 0},t.m=(0,s.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,b.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return O(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const s=i(91144),r=i(4866),n=i(39938),a=i(10508);t.l=(0,r.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,s.decode)(e).payload;if(null==i)throw new Error("Missing payload");const r=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===r));if(null==a)throw new Error("Unknown key");return s.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(b)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const s=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(s)||w.includes(s.toLowerCase())||null!=s.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(s,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const S=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function b(e){return null!=e&&null!=S().exec(e)}t.isValidUid=b,t.SchemeCounts=class{constructor(e){s.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of r(this,s,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return r(this,s,"f").size}addUids(e){for(const t of e)null==v(t)||r(this,s,"f").has(t)||(r(this,s,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},s=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const s=i(11944),r=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),S=i(9483),b=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,s.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,s.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,S.LogLevels.trace))))).map(d.toS).filter((e=>(0,r.notBlank)(e)&&null==e.match(F)))}async function A(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],s=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:s}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,s.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,b.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,A,O,L,B,U,q],s=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of s)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...s]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const s=i(88491);t.UserTimeoutMs=7*s.secondMs},59714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const s=i(43383),r=i(66776),n=i(7162),a=i(29731),o=i(46852),l=i(4586),u=i(82341),c=i(56958),d=i(98462),h=i(33501),f=i(69060),m=(0,s.defer)((()=>(0,n.mkLogger)("writeLicense")));async function p(e,t){return(await(0,o.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,f.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof h.L))}async function g(e,t,i){if(null!=t)if((await p(t,i)).some((t=>t.cmp(e)>=0)))m().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,a.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,c.broadcastEvent_)("reloadLicenses"),m().info("saveIfBetter(): wrote to "+i),i}catch(e){return void m().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,f.vok)(e,"candidate",t);if(null==i)return m().error("!ok",e);await g(i,(0,u.libraryDataDirPosixFile)()?.join((0,f.k)().d),t),await g(i,(0,r.map)((0,l.configDir)(),(e=>d.BaseFile.for(e).join((0,f.k)().d))),t),await f.m.refresh()},t.licensesInDirectory=p,t.saveIfBetter=g},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const s=i(11944),r=i(88491),n=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),S=i(92781);function b(e=10*r.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=b,t.allRecentLogEntries=async function(e=50){(0,S.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-r.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(b(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*r.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,s.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-r.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const s=i(47261),r=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,s.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:s})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const s=i(4866),r=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,s){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:s})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,s.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const s=i(39938),r=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,s.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const s=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:s,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const s of this.loggers())s.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const s=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,s.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const s=i(4866),r=i(27998);t.DefaultLogFormatter=(0,s.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,s.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:s})}}},7258:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),s.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,s,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,s,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+b)}catch(s){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:s})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}s=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const s=i(49411),r=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,s.join)(e??n.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const s=i(4866),r=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,s.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:r.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const s=i(59694),r=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,s.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const s=i(4866),r=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,s.lazy)((()=>new n(r.LogLevels.warn))),t.defaultLogLevel=(0,s.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var s,r=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],s.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,s,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const s=i(88491),r=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*s.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const s=i(11944),r=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,s=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,s).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-s).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,s.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var s,r,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(s.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),r.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,s,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,r,!0,"f")})),this.stream.on("end",(()=>{u(this,r,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,r,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,r,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,s,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,s,"m",l).call(this),t}},r=new WeakMap,n=new WeakMap,a=new WeakMap,s=new WeakSet,o=function(e){if(null===e)u(this,r,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const s=i(87561),r=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),E=i(3955),D=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),A=i(98968),O=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends S.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,A.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,A.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,s.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,A.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,A.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const s=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(s,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:s,end:i}),(e=>(0,A.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const s=i(55413),r=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new s.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),E=i(83837),D=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),A=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,s){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:s})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),s.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,s,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:S.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,s,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,s);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=s&&(r.meta=(0,I.prepMeta)(s)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,A.recentLogEntries)()),(0,A.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,r=new WeakMap,s=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,s,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,s,"m",a).call(this,e,t),c(this,s,"m",u).call(this))},l=async function(){await c(this,s,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,s,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,s,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const s=i(47261),r=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,s.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,s){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:s})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const s=i(39938),r=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,s.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),s=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&s.push({...t,from:i})}return s},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const s=i(4866),r=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,s.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,s.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const s=i(49411),r=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,s.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,n.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const E=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const s=i(4785);t.writeRecentLogEntries=function(){return(0,s.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const s=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...s),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...s]),i}}constructor(e=20){s.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(s=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,s,"m",r).call(this,-1)}get p29(){return n(this,s,"m",r).call(this,-.5)}get p38(){return n(this,s,"m",r).call(this,-.25)}get p84(){return n(this,s,"m",r).call(this,1)}get p98(){return n(this,s,"m",r).call(this,2)}get p99(){return n(this,s,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const s=i(11944),r=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),s=[];for(;e>0;)s.unshift(e%i),e=Math.floor(e/i);return s}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,s.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),s=this.dims.map((e=>e.max)),r=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):s[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),s=this.dims.map((e=>e.max));for(let r=0;r(i[e]+s[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,r.min=n):r.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,s.sum)(e,((i,s)=>t(i,s)?Math.pow(2,e.length-s-1):0))}},31359:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ETA=void 0;const s=i(11944),r=i(88491),n=i(19067),a=i(75556),o=i(7162),l=i(70283),u=i(60346),c=i(6667);t.ETA=class{constructor(){this.remainingMs=new u.Average(10),this.logger=(0,o.mkLogger)("ETA")}push(e){(0,l.mapGt0)(e,(e=>this.remainingMs.push(e)))}clear(){this.remainingMs.clear()}avg(){return(0,c.avg)((0,s.compact)([this.remainingMs.weightedSampleAvg,this.remainingMs.sampleMode]))}fmtEstimate(e=1){return(0,l.mapGt0)(this.avg(),(t=>{const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const s=i(59694),r=i(89965);t.kmeans=function(e,t,i){const n=r(e,t,i);return{...n,centroids:(0,s.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const s=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,s.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,s.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return r(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const s=i(11944),r=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,s){const r=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,s){const n=new a.Average;return l(t,i,s,(t=>(0,r.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,s){const n=[];return l(t,i,s,(t=>(0,r.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,s.range)(r,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,s=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:s/2}),u(e,t,{col:0,row:0},{col:i/2,row:s/2}),u(e,t,{col:0,row:s/2},{col:i/2,row:s}),u(e,t,{col:i/2,row:s/2},{col:i,row:s})];return(0,n.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,s=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:s/2}),c(e,t,{col:0,row:0},{col:i/2,row:s/2}),c(e,t,{col:0,row:s/2},{col:i/2,row:s}),c(e,t,{col:i/2,row:s/2},{col:i,row:s})])},t.greatestHalf=function(e,t){const i=t.col,s=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:s/2}),d(e,t,{col:0,row:0},{col:i/2,row:s}),d(e,t,{col:0,row:s/2},{col:i,row:s}),d(e,t,{col:i/2,row:0},{col:i,row:s})];return(0,n.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const s=[];return l(e,t,i,(e=>s.push(e))),s},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,s.stepRange)(0,t.row,u,(i=>(0,s.stepRange)(0,t.col,o,(s=>(c.clear(),l(t,{col:s,row:i},{col:s+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const s=i(59694),r=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,s){const[r,n,a,o,l]=(0,t.factors)(e),u=(r*i*i+n*i)%s,c=(a*i+o)%s;return Math.round((u*c+l)%s)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,s){const[r,n,a,o,l]=(0,t.factors)(e);return`(((${r}*${i}*${i}+${n}*${i})%${s})*((${a}*${i}+${o})%${s})+${l})%${s}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,s,r,o,l,u,c,h]=d(e%a.SeedCount),f=[i/s,r/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:r.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,s.sortBy)(e,((i,s)=>c(t,s,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,s.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const s=i(6005),r=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const s=[];if(0===t)s.unshift(0);else for(;t>0;)s.unshift(t%e),t=Math.floor(t/e);for(;s.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let s=e;for(;s>u;)t.push(Number(s%i)),s/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,s)=>{i+=e<<8,t[s]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let s=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;s=s*i+BigInt(e)}return t?BigInt(-1)*s:s}randomChars(e){return this.encodeBuffer((0,s.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const s=this.normalizeToken(e),r=this.normalizeToken(t);return s.length>=i&&s===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const s=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,s.toInt)(e)]??(0,r.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const s=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,s.normalizeRotation)(t)?e:new r([...e]).rotate(t).m};class r{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const s=i(6005),r=i(3331);function n(){const e=(0,s.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,r.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,s=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(s+=e)}i++}return s}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){s.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==n(this,r,"f")?e:n(this,r,"f")*n(this,s,"f")/(n(this,s,"f")+1)+e/(n(this,s,"f")+1),"f"),a(this,s,(t=n(this,s,"f"),++t),"f"))}get mean(){return n(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,s=0;for(const r of e)(0,u.isNumber)(r)&&(s++,i+=(r-t)*(r-t));return i/s}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let s=0;s(1-t)*e+t*(i+a*(e-r)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,s=v(t,((t,s)=>(t-i)*(s-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:s/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const s of e)i=null==i?s:i*t+s*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let s=0;se[s]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const s=i(65628),r=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,s.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,s.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=s(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},10309:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.request=void 0;const r=s(i(22286)),n=i(39938),a=i(66776),o=i(9678),l=i(70283),u=i(42041),c=i(79141),d=i(53719);t.request=async function(e,t={}){return null==t.headers&&(t.headers={}),(0,n.blank)(t.headers["user-agent"])&&(t.headers["user-agent"]=o.AppName+" v"+u.version),new Promise(((i,s)=>{const n=r.default.request(e.toString(),t);n.setTimeout((0,a.orElse)(t.timeout,(0,d.commandTimeoutMs)()),(()=>{s(new c.WrappedError("Timeout fetching <"+e+">",{doNotSend:!0,retriable:!0}))})),n.on("response",(e=>{const t=[];e.setEncoding("utf8"),e.on("data",(e=>t.push(e))),e.on("end",(()=>{i({ok:(0,l.within)(200,399,e.statusCode),headers:e.headers,body:t.join(""),statusCode:e.statusCode,statusMessage:e.statusMessage})}))})).on("error",(e=>{s(e)})),(0,a.map)(t.body,(e=>n.write(e))),n.end()}))}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const s=i(70612),r=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,r.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,s.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,r.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,s.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,r.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const s=i(30604),r=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await s.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?s.promises.reverse(e):s.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const s=i(39938),r=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(s.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const s=i(11944),r=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,s.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const s=i(87561),r=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,s.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const s=i(49411),r=i(4866),n=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,n.toS)(__filename).includes((0,s.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const s=i(43383),r=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,s.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,s.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=s(i(70612)),n=s(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=s(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const s=i(39938),r=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,s.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const s=i(4866),r=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,s.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],s=[],r=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?s.push(t):r.push(t)}return{accepted:i,rejected:s,notApplicable:r}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,n.entries)(i))try{if(!1===await s(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:s}){const{accepted:n,rejected:a}=await u.explain(e,...s);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const s=i(61570),r=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,s.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const s=i(11944),r=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,s.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const s=i(4866),r=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,s.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,s.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const s=i(87748),r=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,s.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const s=i(75556),r=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,s.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,s.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const s=i(5712),r=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new s.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new s.Task(e,((i,s,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),s,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const s=i(84253);t.AggregateTypes=(0,s.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const s=i(84253);t.AssetFileSortCriteria=(0,s.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const s=i(39938),r=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const s=i(39938),r=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(s.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const s=i(84253);t.ColorDistanceFunctions=(0,s.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const s=i(42885),r=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.encodeDuration,fromEnv:s.decodeDuration})}get valueOrDefault(){return(0,s.decodeDuration)(super.valueOrDefault)}get value(){return(0,s.decodeDuration)(super.value)}set value(e){super.userValue=(0,s.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,s.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:s.encodeDuration,fromEnv:s.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,s.decodeDuration)(this.defaultValue)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const s=i(38625),r=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,r.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,r.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,s.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const s=i(4866),r=i(39784),n=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,s.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const s=await e.resolve_(),n=await t.resolve_();if(null==s||null==n||n.nativePath===s.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:s?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+s.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await s.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=s.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=s.join("licenses"),t=n.join("licenses");for(const s of(0,r.toA)(await e.childFiles())){const e=t.join(s.base);if(await e.notExists())try{await s.copyFile_(e),i.info("Copied license "+s.base)}catch(e){i.warn("Failed to copy license "+s.base,e)}}}const a=n.join("old");try{const e=await s.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const s=i(4866),r=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,s.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const s=i(39938),r=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,s.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:s.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const s=i(39938),r=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:s.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const s=i(84161);class r extends s.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const s=i(42748),r=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>s.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const r=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const s=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,s.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const s=i(4866),r=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,s.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),s=this.envValue??t;return null!=s&&(i[this.key]=this.opts.toEnv(s)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),s=this.toEnvValue(t);return null!=s&&(i[this.key]=s,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const s=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+s],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const s=i(84253);t.SettingCategories=(0,s.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const s=i(5712),r=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),E=i(7560),D=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),A=i(51053),O=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Q=i(29712),Y=i(26764),Z=i(48995),X=i(18947),ee=i(92438),te=i(22130),ie=i(95888),se=i(7043),re=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new se.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new se.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new se.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new s.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new se.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new se.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new se.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Y.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Q.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new se.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:A.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new se.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new se.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,O.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new se.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new se.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new se.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new se.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,O.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new se.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new se.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Z.ColorDistanceFunctions.ciede2000,strEnum:Z.ColorDistanceFunctions}),dominantColorKmeansRuns:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:X.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Y.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new se.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Q.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new se.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new se.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new se.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new se.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Y.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const s=i(4866),r=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,s.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),E=i(98462),D=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),A=i(95699),O=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,s.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(O.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return X(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,s.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Q()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Z()},t.libraryHasSettings=(0,s.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",H),(0,T.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const s=await e.clear().isNonEmpty(),r=s?e.wip():e;if(await async function(e,i){const s=[(0,g.padding)("#",80)];s.push(...se("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),s.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,s.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),s.push(...e.toTomlLines()),s.push("","")}await e.writeText_("\n"+s.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(r,i),j().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:s}),s){const t=await(0,R.readTomlFile_)(r),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(j().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function Q(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function Y(e){return X(z(e))}async function Z(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const s=await(0,R.readTomlFile_)(e);if(null==s)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,r.compact)((0,p.entries)(s).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,s.lazy)((()=>P.version)),t.writeSystemSettings_=Q,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=ee;const te=(0,s.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function se(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Q()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...se("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...se("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...se("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...se("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let s="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...se((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const s=i(49411),r=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",s.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const s=i(84161);class r extends s.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const s=i(11944),r=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,r.stringify)((0,s.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,s.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const s=i(39938),r=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,s.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const s=i(49411),r=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,n.configDir)(),(e=>(0,s.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const s=i(84253);t.TagInferenceSettingValues=(0,s.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const s=i(81627),r=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,s.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const s=i(39938),r=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,s.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,n.stringifyPretty)(t);return(0,s.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,s.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const s=i(87748);t.valueToS=function(e){return(0,s.stringify)(e,void 0,2)}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const s=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,s.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const s=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,s.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,s.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),E=i(54809),D=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),A=i(43414),O=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(A.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,s.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?A.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:A.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),s=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:s}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:s}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const s of t){let t=e[s],r=s;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[s]?.rawValue})}}const s=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==s)return;const r=i.filter((e=>(0,u.eql)(e.date,s.date)||e.precisionMs<=s.precisionMs&&(0,w.datedOverlap)({a:e.date,b:s.date,aPrecisionMs:e.precisionMs,bPrecisionMs:s.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:s,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(A.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(A.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(A.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const s=await e.mtimeMs();function r(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:s,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!A.Settings.usePathsToInferDates.valueOrDefault||!A.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:A.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,A.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,A.Settings.capturedAtTagsFallback.values))??(n?void 0:r("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:r("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:r("bname",q(e,t)))??(n?void 0:r("path",H(e)))??(A.Settings.useStatToInferDates.valueOrDefault?r("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,A.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const s=i(84253);t.DateTagFormats=(0,s.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const s=i(75556),r=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,s.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),n=s(i(49411)),a=s(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),E=i(21084),D=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),A=i(2023),O=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Q=i(91854),Y=i(54988),Z=i(27446),X=i(84685),ee=i(36062),te=i(15465),ie=i(68107),se=i(26352),re=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const s=i??await(0,te.readMimeType)(e),r=await e.sidecar(),n=(0,Z.isImageMimeType)(s)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Z.isVideoMimeType)(s)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:s,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const s=D.PosixFile.for(e);if(s.isSidecar()&&(i=!1),!await s.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(s.nativePath),void ne().debug("readRawTags("+s+"): invalid file, returning null.");const r=await(0,t._readRawTags)(s.nativePath);if(null==r||!i)return r;ne().trace("readRawTags()",{pf:s,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await s.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,r.tz)]);for(const e of await s.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Z.normalizeMimetype),...r},o=[];for(const[e,i]of n){if(null==i)continue;const s=await i;if(null==s)continue;const r=(0,f.omit)(s,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(s.History)),(0,A.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,A.assignNullishFields)(a,a.inferred),a.Rotation=(0,X.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:s,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,s=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Z.normalizeMimetype);if((0,u.blank)(s))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof r.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,Y.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,Y.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Q.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:s,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,A.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,X.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const s=new h.MultiMap;for(const[r,n]of(0,f.entries)(t)){const t=await me(e,r,i);s.add(t.nativePath,[r,n])}for(const[t,i]of s.entriesArray()){const s=D.PosixFile.for(t),r=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:r}),await le().write(s.nativePath,r,await fe(s)),L.Settings.overwriteOriginal.valueOrDefault||await he(s),s.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,s=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==s)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)}),s.MIMEType=(0,u.mapNotBlank)(s.MIMEType,Z.normalizeMimetype),s.GPSDateTime??(s.GPSDateTime=(0,P.concatDateTime)(s.GPSDateStamp,s.GPSTimeStamp));for(const e of(0,f.keys)(s)){const t=s[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete s[e])}const r=(0,l.compactBlanks)([s.Error,...s.errors??[],s.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(s.problems=r),ae&&(s.__instance=(0,F.safeUUID)()),s}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,s=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,n.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}s.push([a,(0,l.gt0)(o)?o:u])}var r;return S(s)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:s,parser:r}){const n=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+s+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,s.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const s of t)e.set(s,i)}return e})),t.Tag2Synonyms=(0,s.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const s=_(e),n=_(i);if(null==s||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(s),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=s[e],i=n[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:s[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const s=i(39938),r=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,s.blank)(e)||n.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const s=i(4866),r=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,s.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const s=i(84253);t.ExtTypes=(0,s.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const s=i(4866),r=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,s.lazy)((()=>{const e={};for(const[i,s]of(0,o.entries)(t.AllFiletypes))for(const t of s)e[t]=i;return e})),m=(0,s.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,s.lazy)((()=>(0,r.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,s.lazy)((()=>(0,r.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,s.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:s}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,s);for(const i of t.OldBrowserMimetypes)for(const s of t.AllFiletypes[i]??[])e.add(s,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const s of t.AllFiletypes[i]??[])e.add(s,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),s=(0,c.normalizeExt)(t);return null!=i&&null!=s&&(i===s||(p(i)?.includes(s)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:s.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,s]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=s);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function A(e,i,s){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...s??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:s,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:s});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,n.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>s.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const s=F(e);(0,o.blank)(s.nativePath)||(0,P.eqlNameWithoutExt)(s.nativePath,i)?u[t]=s:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,s){const r=D(t.Actions.infer,s),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(s):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:n}),A(i,r,n)},t.ensureHistoryRecords=A},92330:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=s(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),s=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:s,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const s of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[s]);if(null==r||(0,h.isValidDate)(r))continue;const n=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+s+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const s=i(889),r=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),n=s.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??s.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const s=i(84253);t.KeywordReparentingStrategies=(0,s.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const s=i(889),r=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function S(e){return null==e||e instanceof s.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(S)):w(e))}function b(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(b).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=S;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(b))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const s=M(e.Categories);null!=s&&t.push(...s)}for(const s of i){const i=(0,c.pluckDeep)(e,s)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:S(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,s.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),s=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&s.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,n.notBlank)(t)&&s.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&s.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&s.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&s.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of s){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(s,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const s=i(4866),r=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const s=e.replace(t,i);return s===e?e:h(s,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,s.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const s=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=s)return s[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const s=i(889),r=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,r.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function S(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function b(e){return null==e?.op&&S(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=S,t.isPrimitiveRevision=b,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&S(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const s=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==s?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:s,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:s.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let s=i?.[e];const r=[];var l;null!=s&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>r.push(e)));const u=t.every(b)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=s&&s!==i.priorValue&&s!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(s=i.newValue,r.push(`Revision@${i.createdAt}`));return null==s?void 0:{value:s,source:r}}{const e=(0,h.toA)(s);for(const i of t)if("add"===i.op&&null!=i.newValue)r.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){r.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:r}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const s=i(39938),r=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,s.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,s.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,s.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,s.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const s=i(84253);t.NameTagFormats=(0,s.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const s=i(84253);t.NameTagOrders=(0,s.strEnum)("western","eastern")},65308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(66776),l=i(11254),u=i(39784),c=i(7162),d=i(1058),h=i(91464),f=i(6667),m=i(43414),p=(0,s.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Zโ€˜โ€™']+[-A-Zโ€˜โ€™']{2})\b/,S=/^[()[\]/.\-_]+$/;function b(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),s=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],S=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,r.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let b;function M(e){(null==b||b>e.matchedIndex)&&(b=(0,f.min)([b,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(M(e),S.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,r.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),S.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(b=void 0,S.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),S.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,r.mapNotEmpty)((0,r.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),S.push(i.captured),t=i.unmatched.trim())}null!=b&&t.length>b&&(0,r.mapNotEmpty)((0,r.compactBlanks)(t.slice(b).split(/\s+/)),(e=>{S.push(...e),t=t.slice(0,b)}));const _=(0,r.compactBlanks)(t.split(/\s+/)),T=l.length,E=S.length;if(_.length>0)if(0===T&&E>0)l.push(..._);else if(0===E&&T>0&&1===_.length)S.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;S.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:s,lifespan:i,familyNames:P(S),minFamilyNameIndex:b}}function P(e){return(0,r.uniq)((0,r.compactBlanks)(e).filter((e=>null==S.exec(e))))}function M(e){let t="";for(const i of(0,r.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=b,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=b(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),s=M(t.givenNames);return(0,r.compactBlanks)((0,r.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([s,e]):_(t,s,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const s=i(33714),r=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,s.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,s.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,s.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,s.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const s=i(66776),r=i(75556),n=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,s.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const s=i(4866),r=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,s.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const s=i(11944),r=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,s.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,s.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const s=(0,a.commonPrefixIgnoreCase)(e,i);if(s.length<8)return!1;function n(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(s.length)),l=n(i.slice(s.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const s=i(4866),r=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,s.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,s.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const s=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,s,await(0,h.rawInfo)(e));const n=b(i,s);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const s=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==s)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:s}});const r=(0,a.maybeDimSwap)(s,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:s,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const s=i(82798),r=i(61473);t.tag_fts_root=function(e){const t=(0,s.toS)(e).indexOf(r.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,s.toS)(e).split(r.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const s=i(889),r=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),E=i(75123),D=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),A=i(96593),O=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of s){const s=(0,L.extractMakeAndModel)(await(0,A.readRawTags)(t));if((0,f.definedAndNotEql)(s.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:s});else if((0,f.definedAndNotEql)(s.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:s});else if(null!=s.Make&&null!=s.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:s,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),s=await z(t?.older);return null==i||null==s?void 0:{before:i,after:s,index:i.index,slots:i.index+s.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),r=(0,D.findFileIndex)(e,s);if(r<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[s.slice(r-2*t,r),s.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,A.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==s.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const s=await e.stat();if(null!=s){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:s[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:s}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:s}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const s=i[e];if(null!=s&&!0===(0,v.datedOverlap)({a:t,b:s}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(s)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,s.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,s.last)(e)):(0,s.last)(g(e))}function w(e,t){if((0,s.isEmpty)(e)||(0,s.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,s.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,s.uniqBy)((0,l.toA)(e),(e=>(0,s.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,s.compact)(t).map((e=>y(e))));return(0,s.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(s.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const s=i(11944),r=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,s.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const s of i){const i=(0,a.toS)(e[s]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,s.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const s=i(49411),r=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,s,r,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(s??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:s,query:r,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===s?s=this.path:null===s&&(s=g),void 0===r?r=this.query:null===r&&(r=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&s===this.path&&r===this.query&&n===this.fragment?this:new b(t,i,s,r,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const s=i[2]||g,r=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===s&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new b(s,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(s.win32.join(T(e,!0),...t)).path:s.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,s=-1;for(let r=0;r=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==s&&(i+=encodeURIComponent(e.substring(s,r)),s=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[n];void 0!==t?(-1!==s&&(i+=encodeURIComponent(e.substring(s,r)),s=-1),i+=t):-1===s&&(s=r)}}return-1!==s&&(i+=encodeURIComponent(e.substring(s))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let s="";const{scheme:r,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(s+=r,s+=":"),(l||"file"===r)&&(s+=y,s+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?s+=i(t,!1):(s+=i(t.substr(0,e),!1),s+=":",s+=i(t.substr(e+1),!1)),s+="@"}e=l.indexOf(":"),-1===e?s+=i(l,!1):(s+=i(l.substr(0,e),!1),s+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}s+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>s+="?"+e)),o&&(s+="#",s+=t?o:M(o,!1)),s}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const s=i(4866),r=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,s.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),s=(0,c.toURI)(t);return i.scheme===s.scheme&&i.authority===s.authority&&f(i.path,s.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const s=i(49411),r=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,s.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),s=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(s.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(s.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?s.win32.sep:s.posix.sep,n=(0,r.notBlank)(t)&&!t.includes(i);if(n&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const s=i(11944),r=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,s.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),s=t.join(i);if(s.isFileSync())return s.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return s.nativePath}},30848:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),s=i[0];if((0,o.blank)(s))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,s)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const s=i(39938),r=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,s.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const s=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(s.version)},t.baseVersion=()=>[s.versionMajor,s.versionMinor,s.versionPatch].join("."),t.versionMajorMinor=s.versionMajor+"."+s.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const s=i(10912),r=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof s.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,s.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,s.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof s.SemVer?e:(0,s.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const s=i(84253);t.UpdateChannels=(0,s.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const s=i(11944),r=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,s.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const s=i(3874),r=i(55412),n=i(46573);t.currentVolumeRoots=(0,r.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const r=(await(0,s.nativePath2uri)(i.mountpoint,i))?.toString();null!=r&&e.push(r)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const s=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,s.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const s=i(4866),r=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),s=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||s||r);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:s,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,s.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],s=m(e["1024-blocks"])??0;if(0===s)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,n=m(e.Available)??0;if(0!==r||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?r+n:s,used:r,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:s,used:r,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const s=["-k","-P"];if(!0===e&&s.push("-l"),s.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",s,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,s.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await A()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),s=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:s,status:i},meta:{input:e}});var n}async function A(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(k)),s=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(s).map(I)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=A},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),E=i(53719);t.isGioSupported=(0,s.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,s.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const s=await k(i.mountpoint);return null==s?i:{remote:!0,...i,...s}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),s=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(s,(e=>e.hostname)),remoteShare:(0,u.opt)(s).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const s=i(4866),r=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,s.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const s=i(4866),r=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,s.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),s=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==s)return;const n=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const r=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...r,...n},u=s?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:n,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,s.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,s.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),s=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=s?{used:i,available:s,size:i+s}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const s=i(55543),r=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,s.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const s=i(4866),r=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),E=i(43414),D=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),A=(0,s.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function O(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){O(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,s.lazy)((async()=>{E.Settings.libraryDir.watchLater(O),E.Settings.scanPaths.watchLater(O),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,s.lazy)((()=>{}));t.mountpoints_=(0,s.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,s.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],s=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,s):i.includes(s)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),O()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,s.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,s.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const s=i(4866),r=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,s.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=T){if(g.isLinux)try{const s=await(0,f.readLines_)(e),n=(0,r.compact)(s.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,s])=>{const r=t(e),n=await i(s);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&n,meta:{fs:e,mp:s,fsOK:r,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,s.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const s=i(4866),r=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,s.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const s=i(4866),r=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,s.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],s=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(s)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const s=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,s.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,s.blank)(i.remoteHost)&&!(0,s.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,s.blank)(e)&&!(0,s.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const s=i(11944),r=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,s.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,s.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(s=>({mountpoint:(0,y.ensureSuffix)(s[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const s=i(88491),r=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/s.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,s.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),s=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=s)return P().tap({msg:"Serving UUID from "+t,result:s,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=s(i(70612)),n=s(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),E=i(91464),D=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),A=i(20902),O=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Q=i(55412),Y=i(11142),Z=i(71820),X=i(32421),ee=i(92002),te=i(76019),ie=i(53719),se=i(27127),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),ne=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const s=i.get(e);null!=s&&(0,p.gt)(s.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Q.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Q.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const s=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:s,os:ne}))),n=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const s=e.join(t+".json");try{await s.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:s.nativePath,vol:i}),await s.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),s=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,s))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:n}),r||n?void 0:e}async function pe(e,i){const s=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(s))return;const r=await(0,R.actualPath)(s);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const s=t.find((e=>e.mountpoint===i));if(null!=s)return re().debug("bestVolumeForPath()",{nativePath:r,result:s.mountpoint,src:e.name}),s}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const s=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(s))return;const r=s.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const n=await(0,U.friendlyname)(e);return(0,D.asyncFind)(s,(async e=>(0,E.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),s=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:s.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Q.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,O.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,O.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,O.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,se.addVolumeUUIDs)(i);const s=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:s}),s.forEach(ce),await fe(s),Object.freeze(s)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const s=i(49411),r=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,s.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,s.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const s=i(84253);t.HelmetPlugins=(0,s.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const s=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,s.within)(200,299,e),success:e=>(0,s.within)(200,299,e),redirect:e=>(0,s.within)(300,399,e),clientError:e=>(0,s.within)(400,499,e),serverError:e=>(0,s.within)(500,599,e),error:e=>(0,s.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const s=i(11254),r=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?s.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,r.compactBlanks)([s.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const s=i(4866),r=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,r.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,s.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),s=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,r.isEmpty)(s))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(s));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const s=i(49411),r=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,s.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const s of e)s.lengthe.includes(t)));if(null!=t)return t;for(let t=0;ts.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const s=i(39938),r=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,s.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,r.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const s of e)t+=i[s]?.[0]??s;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=s(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),S=i(91641),b=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),E=i(59387),D=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{D().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(1.2*_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,s,"m",o).call(this),intervalMs:((0,E.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),s.add(this),r.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,r,"f").push(e))),l(this,s,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,r,"f").sampleAvg??F()}}t.CpuUsage=x,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,r,"f").push(e)},o=function(){l(this,s,"m",a).call(this,F());const e=new C;l(this,s,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const s of e)t+=s.times.user+s.times.nice+s.times.sys+s.times.irq,i+=s.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,s=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(s)?Math.round(t/s*100):void D().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+b.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:s})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},76052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const s=i(4691),r=i(44606),n=i(11053);t.doNotRun=function(e){return null!=o(e)};const a=["error","no-library","stop-sync"];function o(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,n.isTooBusy)())return"system is too busy";const t=(0,r.getRemoteOrLocalHealthSummarySync)();return null!=t&&a.includes(t.level)?t.level+": "+t.msg.join("\n"):void 0}t.whyDoNotRun=o},21003:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=s(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const s=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(s))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([s,i]),meta:{freemem:e,totalmem:t,cgroupMem:s}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const s=i(79015);let r=!1;function n(){r&&(r=!1,(0,s.ee)().emit("clearCache"),(0,s.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?n():r||(r=!0,(0,s.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const s=i(4866),r=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,s.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,s.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,s.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,s=S();if(1!==s){const e=t;t*=s,y().warn("Recent timeouts! Throttling down.",{penalization:s,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:s,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,s.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,s.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const s=i(5712),r=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new s.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},84213:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(5712),o=i(79378),l=i(4866),u=i(7162),c=i(79015),d=i(51081),h=i(24409),f=i(11944),m=i(16475),p=i(87748),g=i(75556),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,s,"m",r).call(this,e))),s.add(this),this.request=e}}t.RequestTask=v,s=new WeakSet,r=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},29144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=t.workerMethodTimeouts=void 0;const s=i(4866),r=i(92585),n=i(61570),a=i(20636),o=i(12374),l=i(7162),u=i(55568),c=i(4691),d=i(49379),h=i(84571),f=i(43414),m=i(59387),p=i(98023),g=i(84213),y=i(48392),v=i(48011),w=(0,s.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let S=0;const b=[[v.WorkRequestMethods.buildAssetPreviews_,f.Settings.taskTimeoutMs.valueOrDefault]];async function P(e,...i){let s=(await(0,y.WorkerCluster)()).t;if(s.ended){if((0,c.ending)())return w().warn("onChild(): cluster is ended, running task myself",{method:e,args:i}),v.WorkerFunctions[e](...i);w().warn("onChild(): cluster ended unexpectedly. Restarting.",{method:e,args:i}),s=(await y.WorkerCluster.refresh()).t}const n=(0,t.workerMethodTimeouts)().get(e)??(0,h.statTimeoutMs)(),o={id:S++,method:e,args:i};return(0,r.retryOnReject_)((async()=>{const e=new g.RequestTask(o),t=s.enqueueTask(e);return(0,a.thenOrOnTimeout)(t,n/3,(()=>{w().warn("soft timeout servicing work request",{request:o,timeoutMs:n}),(0,p.onTimeout)()})),(0,a.thenOrTimeoutError)(t,n)}),{maxRetries:f.Settings.maxRetries.valueOrDefault,timeoutMs:n,retryDelay:f.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,d.isRetriableError)(e)})}function M(){for(const e of(0,n.values)(v.WorkerFunctions))e.setShim(void 0)}t.workerMethodTimeouts=(0,s.lazy)((()=>new Map(b))),t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,m.singleThreadMode)()||(0,u.isWorkerService)())w().warn("in single-threaded mode"),M(),await((await y.WorkerCluster.prior())?.end());else for(const[e,t]of(0,n.entries)(v.WorkerFunctions))t.setShim((t=>P(e,t)))},t.clearShims=M},48011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const s=i(75556),r=i(61570),n=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,n.strEnum)(...(0,r.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)}},48392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerCluster=t.workerClusterPriorEnd=void 0;const s=i(5712),r=i(13056),n=i(4866),a=i(7162),o=i(38307),l=i(91641),u=i(69317),c=i(95237),d=i(53525),h=i(51081),f=i(24409),m=i(29663),p=i(59387),g=i(88491),y=i(87748),v=i(75556),w=i(2934),S=i(82798),b=i(24905),P=i(94845),M=i(43414),_=i(75153),T=i(941),E=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.WorkerCluster.prior())?.t.closeChildProcesses()},t.WorkerCluster=(0,n.lazy)((async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return E().throw("Could not find worker.js");E().info("worker.js found at "+e);const t={id:-1,method:"ping",args:[{}]},i=new s.BatchCluster({processFactory:async()=>(E().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,T.workerEnv)()})),...(0,r.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,P.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:b.ChildServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,S.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,_.cpuCount)(),e??(0,p.maxCpus)());return E().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new r.BatchClusterObserver("worker",i,l.EndableRanks.first)}))},941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const s=i(10347),r=i(43414),n=i(32421),a=i(38625),o=i(61570);t.workerEnv=async function(){const e={};for(const t of(0,o.values)(r.Settings))t.hasValue()&&!(0,a.isTrue)(t.opts.transient)&&t.addToEnvMaybe(e);return r.Settings.libraryDir.addToEnv(e),r.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,s.childEnv)({overrides:e,forWorker:!0})}},45766:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=s(i(97742)),n=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const s=i(59694),r=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const s=e[t];return e.splice(t,1),e.splice(i,0,s),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const s of e)if(null!=s){const e=t(s);null!=e&&(0,o.getOrSet)(i,e,(()=>s))}return[...i.values()]}function P(e,t,i=1,s=(e=>e)){const r=[];if(et;n-=i)r.push(s(n));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,s.sortBy)(e,g),r=(0,s.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const s=e.map(i);for(const r of t){const t=i(r);s.includes(t)||(e.push(r),s.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let s=0;s0)return e.splice(s,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,s.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,s.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const s of e)if(null!=s){const e=t(s);null!=e&&i.set(e,s)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const s of e)null!=s&&i.every((e=>!t(s,e)))&&i.push(s);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,s)=>e+(t(i,s)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,s)=>e+t(i,s)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const s=Math.round(i);if(s<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,s=t.primitiveValueOfOrElse){const r=new Set(i.map(s));return e.filter((e=>!r.has(s(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const s=i(11944),r=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const s of e)(0,o.getOrSet)(i,(0,a.stringify)(t(s)),(()=>s));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,s.compact)(e),s.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,s)=>0===s||t(i)>=t(e[s-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const s=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const s=i(47025);t.asPromise=async function(e){const t=await e;return(0,s.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const s=i(88012),r=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const s=(0,c.toS)(e.v);return(0,n.blank)(s)||"1"===s||(i??(i=new URLSearchParams)).append("v",s),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,s.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,s.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,s.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:n,af:l}){if(null==(0,s.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const S=n&&(0,f.isSafari)((0,h.ua)());S?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const b=r.map((s=>m(y({assetId:e,params:t,reducer:i,width:s}),s)));return null!=l&&b.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(S?"data-":"")+"srcSet"]=b.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,s.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:s="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===s?80:"m"===s?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const s=i(43947),r=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,s.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,s.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const s=i(66776),r=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,s.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function s(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!s(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=s,t.isDisabled=function(e){return s(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):s(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const s=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,s.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const s=i(11944),r=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const s=Math.floor(e/t.hourMs);e-=s*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(s)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},s=10*i(),r=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,r,s)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/s.ms);e-=n*s.ms,n>0&&(s.ms>=t.dayMs?i:r).push(n+s.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,s.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const s=i(38625),r=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const s=i.get(e)?.get(t);return"boolean"==typeof s?s:null}function a(e,t,i,s){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,s):(r=new WeakMap,r.set(t,s),i.set(e,r))}function o(e,t,i,s){if(null!=i?.comparator)return u(e,t,i,s);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,s){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,s);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,s){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],s);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,s);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,s);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),s);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),s);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const s=[],r=[];return e.forEach((function(e,t){s.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(s.sort(),r.sort(),i)}(e,t,s);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,s)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const s=e.length;if(s!==t.length)return!1;if(0===s)return!0;let r=-1;for(;++r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,s=!1;const r=function(){if(s){if(null!=i)throw i;return t}try{return s=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const s=i(88491),r=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>s.secondMs&&t&&r.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=s.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const s=i(75556),r=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,s.toGt0)(e?.width)??0)*((0,s.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,s.gt0)(e)&&(0,s.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const s=i(85120),r=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,s.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const s=l.get(i);if(null!=s)return s(e,t)??null}for(const i of o){const s=i(e,t);if(null!=s)return s}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const s=i(11944),r=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,s.uniq)((0,s.compactBlankish)((0,n.flatten)((0,s.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,s.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const s=i(39784);t.flatten=function(e,t=[]){for(const i of(0,s.toA)(e))if(null!=i)for(const e of(0,s.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const s=i(11944),r=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,s.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,s.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const s=i(11944);function r(e,t){return null==(e=(0,s.uniq)((0,s.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const s=i(39938),r=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,s.blank)(e.id)&&!(0,s.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,s.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const s=i(84253);t.ReducerNames=(0,s.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const s=i(84253);t.FitSizes=(0,s.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,s.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const s=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,s.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,s.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(s,r){if((0,isFunction_1.isFunction)(s))return;let n,a,o,l=toJSON(s);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(s===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const s=i(11944),r=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,s.isEmpty)(l))return;const n=await e,o=await i;if(!(0,r.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const s=i();return null!=s&&e.set(t,s),s}},t.deleteIf=function(e,t){for(const[i,s]of e.entries())t(i,s)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const s=i(90957),r=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,s.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,s){return null==e||null==t||null==i?void 0:s(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,s.tot)(i)},t.map2Or=function(e,t,i,s){return o(a(e,t,i),s)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const s=i(11944),r=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,s]of Object.entries(e))t.add(i,...s);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,s.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,s.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const s=i.filter((e=>!(0,n.eql)(e,t)));return 0===s.length?this.store.delete(e):this.store.set(e,s),i.length!==s.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,s.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,s.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,s.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const n=r.length;(0,s.filterInPlace)(r,(t=>e(i,t))),t=t||n!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const s of i)e.add(s,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,s]of this.entries())s.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const s=i(59694),r=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,s.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const s=(0===t?1e-5:t)*(1-i);return m(t-s,t+s,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),s=Math.pow(10,Math.abs(i));return i<0?_(e/s)*s:_(e*s)/s},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const s=i(11944),r=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,s]=i;null!=e&&void 0!==s&&("object"!=typeof t&&(t={}),t[e]=s)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,s.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,s.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,s.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,s.uniq)((0,s.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[s,r]of g(t))!0!==i?.omitKeys?.includes(s)&&(null==r&&!0!==i?.assignNullish||(e[s]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const s of i){const i=t[s];void 0!==i&&void 0===e[s]&&(e[s]=i)}return e},t.assignAllFields=function(e,t){for(const[i,s]of g(t??{}))e[i]=s;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,s.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,s.compact)(t.map(e));{const i=(0,s.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,s.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const s of t)void 0!==e[s]&&(i[s]=e[s]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const s of t)void 0!==e[s]&&(i[s]=e[s]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const s of t){const t=e[s];(0,n.notBlank)(t)&&(i[s]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const s of t)if(i(e[s]))return e[s]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const s={};function r(e,t){if(null==t)return;const i=s[e];s[e]=null==i?t:S(i,t)}for(const s of i){const[i,a]=(0,c.splitFirst)(s,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const s of h(t))((0,l.toInt)(s)??-1)>=0&&r(s,e(t[s],...i));return s},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const r=(0,s.compact)(t.map((t=>e(t,i))));return(0,s.isEmpty)(r)?void 0:{key:r[0].key,value:(0,s.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,s.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,s.uniq)(t)},t.maybeCall=function(e,t,...i){const s=e?.[t];return(0,a.isFunction)(s)?s.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),s=p(i);return 1===s.length?s[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class s{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new s(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,s){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>s(this.a,e,t,i)))))))}}function r(e){return e instanceof s||e===t.None}function n(e){return r(e)?e:null!=e?new s(e):t.None}t.Some=s,t.isOpt=r,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const s=i(75556),r=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,r.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,s.toInt)((0,n.toS)(e));return(0,s.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const s=i(75556),r=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,s.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const s=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,s.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const s=i(11944),r=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const s=typeof e,n=typeof i;if(!("string"!==s&&"symbol"!==s||"string"!==n&&"symbol"!==n)){const s=(0,r.toS)(e),n=(0,r.toS)(i),a=s.localeCompare(n);return s[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):s!==n?o.indexOf(s)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const s=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,s.toA)(await e))if(null!=r){const e=await r;if(null!=e){const s=await t(e);null!=s&&i.push(s)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const s=await e;return t(s)?i(s):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const s=i(84253);t.PromiseStates=(0,s.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const s=i(11944),r=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,s){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(s??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const s of o(0,e.length,t))i.push(e[s]);return i},t.pickWeightedRandom=function(e){if((0,s.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,s.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let s=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,s=s.slice(0,r.index)+i(r)+s.slice(r.index+r[0].length);return s}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const s=i(75556);function r(e){if(!(0,s.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,s.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const s=i(84253);t.RunStates=(0,s.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const s=i(84253);t.ServiceNames=(0,s.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const s=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,s.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),s=a(t);return null==i||null==s?void 0:i>s?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const s=i(11944),r=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const s=f();return null!=s?(0,o.sliceIterable)(s.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),s=(0,c.toS)(t);return s.length>0&&i.startsWith(s)?i.slice(s.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),s=(0,c.toS)(t);return s.length>0&&i.endsWith(s)?i.slice(0,-s.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let s=i;s>=0;s--)if(m(e,s).startsWith(t))return s;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const s=(0,c.toS)(e),r=(0,c.toS)(t);return s.length===r.length&&(s===r||s.toLowerCase()===r.toLowerCase()||"function"==typeof s.localeCompare&&0===(i?s.normalize():s).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,s.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const s=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&s.startsWith(t))return e(s.slice(t.length),i);return s},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const s=p(e);return s.length<=t?s.join(""):s.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?s.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const s=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const s=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(s.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=s)return[t];const n=S(t," ",s);if(n>r.length)return[m(t,0,n),...e(m(t,n+1),i)];{const s=t.indexOf(" ",r.length+1);return s>0&&s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const s=i(88491),r=i(61570),n=i(90957),a=i(21669);async function o(e,i,s=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{s&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const n=await o(e,i,r);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,s.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,s=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,s)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(s,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{s(await i())}catch(e){n(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),s(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,s.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:s,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,n.tot)(s):a}},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const s=i(47025);t.tot=function(e){return(0,s.isFunction)(e)?e():e},t.tol=async function(e){return(0,s.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const s=i(11944),r=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,s.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,s]of e.entries())i.set(t,s);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const s=i(39938),r=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const s of e)(0,n.isNumber)(s)&&(i+=s/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,s.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),s=Math.floor(i/3),r=Math.pow(10,3*s),a=d[s];return(0,n.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),s=Math.floor(i/10),r=Math.pow(2,10*s),a=h[s];return(0,n.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,s.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const s=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,s.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const s=i(11448),r=i(82798);t.ua=(0,s.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,s=/\bSafari\b/,r=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,s)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const s=i(66776),r=i(75556);function n(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,s.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},42313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const s=i(84253);t.SyncStatuses=(0,s.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const s=i(84253);t.S=(0,s.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const s=i(59694),r=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,s.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,r.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const s=i(11944),r=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const s=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(s?.get("seed"))){const e=(0,t.urlSeed)().toString();return s?.set("seed",e),s??{seed:e}}return s}function u(e,t,i=!1){const s=c(e,t,i);return(0,o.assembleFullPath)(s.path,s.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,s.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,r.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const s=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,s.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const s=i(11944),r=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,s.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const s=i(87748);t.toS=function(e){return n(e,",")};const r={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==r?e.toString():(0,s.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const s=i(4866),r=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),S=i(43414),b=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),E=i(94332),D=i(63216),k=(0,s.lazy)((()=>(0,r.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,D.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,s.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:S.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,s.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:S.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,s.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(S.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,s.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),A=(0,s.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),O=(0,s.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(S.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,s.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,s.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:S.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,s.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,b.compact)([x(),C(),F(),I(),A(),(0,w.LogDirCleanup)(),O(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,s.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},64303:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceRebuildLibrary=void 0;const s=i(93813),r=i(30690),n=i(89452),a=i(36310);t.forceRebuildLibrary=function(){r.Asset.dbl.runf((e=>e.update({version:0}))),n.AssetFile.dbl.runf((e=>e.update({version:0}))),a.Operation.dbl.runf((e=>e.where({name:a.OperationNames.enqueueAssetFileUpdates,version:s.AssetFileVersion}).orWhere({name:a.OperationNames.enqueueAssetUpdates,version:s.AssetVersion}).delete()))}},49374:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),S=i(49441),b=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),E=i(46573),D=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),A=i(61570),O=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,s,"f",r)?.rootDir.nativePath,i=!0===a(this,s,"f",r)?.isReadySync(),n=!0===a(this,s,"f",r)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,s,"f",r):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,s,"f",r)),o(this,s,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new s(e),"f",r))}static get priorInstance(){return a(this,s,"f",r)}static endPriorInstance(){const e=a(this,s,"f",r);return o(this,s,void 0,"f",r),(0,l.end)(e)}static async instanceReady(){const e=s.instance();return await(e?.ready),e}static instanceRequired(){const e=s.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,S.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,A.tap)(new b.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>b.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,s=j,n=new WeakMap,r={value:void 0}},93445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const s=i(23872),r=i(31216),n=i(9069),a=i(13222);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,s.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:r.isValidFile}),i}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const s=i(19658),r=i(20902),n=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,r.isEnvTrue)("ENABLE_SENTRY")||s.isProd&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),S=i(91641),b=i(95557),P=i(4691),M=i(52289),_=i(10408),T=i(27519),E=i(49379),D=i(17875),k=i(79015),x=i(12737),C=i(49857),F=i(7157),I=i(85352),A=i(9483),O=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const s=await Z(e);return await(T.ErrorStore.instance()?.maybeSendEvent(s))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new b.EndableWrapper("EventFilter",(()=>this.end()),S.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Q(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Q(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await X());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function X(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Q,t.sentryExceptionToS=Y,t.annotateEvent=Z,t.mkBreadcrumbs=X,t.logEntryToBreadcrumb=ee;const te=new Map([[A.LogLevels.fatal,"fatal"],[A.LogLevels.error,"error"],[A.LogLevels.warn,"warning"],[A.LogLevels.info,"info"],[A.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),S=i(7162),b=i(33148),P=i(55568),M=i(25516),_=i(38307),T=i(42041),E=i(95557),D=i(4691),k=i(2126),x=i(7383),C=i(70259),F=i(24905),I=i(44731),A=i(20902),O=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Q=i(39938),Y=i(88491),Z=i(43947),X=i(6314),ee=i(66776),te=i(50530),ie=i(82798),se=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{x.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,k.exit)({reason:"exit() event",status:0})))}));class re extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,s,"m",l).call(this))),s.add(this),this.opts=e,r.set(this,void 0),n.set(this,new X.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup()",(()=>m(this,s,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,s,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,r,(0,S.mkLogger)("Service("+this.name+")"),"f"),m(this,s,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,n,"f").promise}get isReady(){return m(this,n,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=re,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,s=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Q.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Q.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new B.WrappedError(e)}),5*Y.secondMs)})),(0,b.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,s,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,n,"f").reject():m(this,n,"f").resolve()}catch(e){console.error((0,O.errorToS)(e)),m(this,n,"f").reject((0,te.toErr)(e)),(0,k.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,O.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,se.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,Z.later)((()=>(0,k.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,r,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,r,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,r,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},13902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const s=i(4866),r=i(7162),n=i(80294),a=i(82341),o=i(43414),l=i(82041),u=i(53719),c=i(46573),d=i(88491),h=i(75556),f=i(17078),m=(0,s.lazy)((()=>(0,r.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const s of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const r=await(0,c.bestVolumeForPath)(s,t);if(null==r)return void m().warn("Can't find volume for "+s+", using default TTL for volumes()");if(r.available{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const s=i(4866),r=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,s.lazy)((()=>(0,r.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function S(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},s=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),r=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+s);return e?(await(0,d.writeTextfile_)(r.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+r),r):r}async function b(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=S,t.vacuumStatDbDirs=async function(){const e=await S();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||ig(this,d,"f").call(this),intervalMs:7*z.secondMs,onEnd:()=>g(this,s,"m",n).call(this),rank:D.EndableRanks.first,endTimeoutMs:M.ShortCommandTimeoutMs}),s.add(this),this.queueNames=e,this._processItem=t,this.processRate=new w.Rate,this.processMs=new A.Average,this.ee=new S.default.EventEmitter,r.set(this,!1),this.recentlyProcessed=new T.TTLArray(z.minuteMs),this.on=this.ee.on.bind(this.ee),this.queues=(0,b.lazy)((()=>q.Queue.ops().upsert((0,B.compactBlanks)(this.queueNames).map((e=>({name:e})))))),this.queueIds=(0,b.lazy)((()=>this.queues().map((e=>e.id)))),this.queueItemCount=(0,b.lazy)((()=>{const e=this.queueIds();return H.QueueItem.dbl.pluckFirstf((t=>t.countDistinct("id").whereIn("queueId",e)))})),u.set(this,(0,b.lazy)((()=>{this.logger.debug("status",this.state())}),(P.isTest?1:30)*z.secondMs)),d.set(this,(0,b.lazy)((()=>setTimeout((()=>{g(this,s,"m",o).call(this),g(this,d,"f").unset(),g(this,s,"m",m).call(this)}),100)))),h.set(this,(()=>g(this,d,"f").call(this))),f.set(this,(0,b.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,R.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,O.isTooBusy)(),whyDoNotRun:(0,L.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.queueItemCount(),freeSlots:this.p.freeSlots()})),(P.isTest?1:30)*z.secondMs)),this.p=new x.Promises(c,i?N.maxConcurrentImports:()=>1),this.p.ee.on("vacancy",(()=>g(this,d,"f").call(this))),this.p.ee.on("drain",(()=>g(this,s,"m",a).call(this))),!0===l&&this.awaitDrain().then((()=>this.end())),(0,I.ee)().on("resume",g(this,h,"f"))}async awaitDrain(){if(this.isDone())return;const e=new W.Latch;this.ee.once("drain",(()=>e.resolve())),g(this,d,"f").call(this),await e.promise}isDone(){return this.ended||g(this,r,"f")}isRunnable(){return!this.isDone()&&!this.p.isFull()}findQueue_(e){const t=this.queues();if((0,j.blank)(e))return t[0];const i=t.find((t=>t.name===e));if(null==i)throw new C.InternalError("WorkQueue: unknown queue name "+(0,V.stringify)(e));return i}enqueueWork(e,t){const i=this.findQueue_(t);this.logger.debug("enqueueWork()",{items:e,queue:i});const s=i.upsertWorkItems(e);return y(this,r,!1,"f"),g(this,d,"f").call(this),s}get recentFileProgress(){return this.recentlyProcessed.map((e=>e.contents))}processedCount(){return this.processRate.eventCount}currentWorkCount(){return this.p.pendingWithName(this.name).length}pendingWorkCount(){return this.queueItemCount()-this.currentWorkCount()}percents(){const e=this.processedCount(),t=this.queueItemCount(),i=(0,U.round)(e/(t+e)*100);return{done:e,todo:t,completePct:i,incompletePct:100-i}}currentQueueItems(){return this.p.payloadsWithName(this.name)}currentQueueContents(){return this.currentQueueItems().map((e=>e.contents))}currentQueueItemIds(){return this.currentQueueItems().map((e=>e.id))}etaMs(){const e=this.processMs.n<=6?void 0:this.processMs.p84;return null==e?void 0:this.queueItemCount()*e}state(){return{...this.p.stats(),isDone:g(this,s,"m",a).call(this),freeSlots:this.p.freeSlots(),currentWork:this.currentQueueContents(),pendingWork:this.queueItemCount(),next10:g(this,s,"m",c).call(this,10).map((e=>e.contents)),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.contents)),isRunnable:this.isRunnable(),...this.percents(),etaMs:this.etaMs()}}doNotStartMoreWork(){return(0,R.isPaused)()||this.p.isFull()||(0,O.isTooBusy)()||(0,L.doNotRun)(this)||0===this.pendingWorkCount()}}t.WorkQueue=G,r=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,s=new WeakSet,n=function(){return(0,I.ee)().off("resume",g(this,h,"f")),this.awaitDrain()},a=function(){if(this.ended)return!0;const e=g(this,r,"f");return y(this,r,0===this.currentWorkCount()&&0===this.queueItemCount()&&0===this.queueItemCount.refresh(),"f"),!e&&g(this,r,"f")&&(g(this,u,"f").refresh(),this.ee.emit("drain")),g(this,r,"f")},o=function(){this.queueItemCount.unset()},l=function(e){e.delete(),this.logger.info("postProcessItem()",{item:e}),g(this,d,"f").call(this)},c=function(e){return 0===e?[]:H.QueueItem.ops().allf((t=>(t=t.distinct().whereIn("queueId",this.queueIds()).andWhere((e=>e.whereNotIn("id",this.currentQueueItemIds()))).orderBy("id"),(0,U.gt0)(e)&&(t=t.limit(e)),t)))},m=function(){if(this.doNotStartMoreWork())g(this,f,"f").call(this);else{g(this,u,"f").call(this);const e=this.p.freeSlots(),t=g(this,s,"m",c).call(this,e);this.logger.debug("runChunk():",{freeSlots:e,next:t});for(const e of t)this.p.enqueue({name:this.name,payload:e,l:()=>g(this,s,"m",p).call(this,e)})}g(this,s,"m",a).call(this)},p=async function(e){try{const t=Date.now();await this._processItem(e);const i=Date.now()-t;this.recentlyProcessed.push(e),this.processRate.onEvent(),this.processMs.push(i),this.ee.emit("processed",e,i)}catch(t){(0,F.onError)(this.name+" failed to process item "+e.contents,t)}finally{(0,k.ending)()||g(this,s,"m",l).call(this,e)}}},26367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DropWorkQueuesArg=void 0;const s=i(43414),r=i(38625);t.DropWorkQueuesArg={beforeParse:e=>e.option("--drop-queues","Before starting, all previously-enqueued, incomplete work will be deleted."),afterParse:async e=>{(0,r.isTrue)(e.dropQueues)&&(s.Settings.dropWorkQueues.envValue=!0)}}},12182:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDone=void 0,t.ExitWhenDone="--exit-when-done"},78877:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDoneArg=void 0;const s=i(43414),r=i(38625),n=i(12182);t.ExitWhenDoneArg={beforeParse:e=>e.option(n.ExitWhenDone,"Exit after jobs are completed. Defaults to false unless paths are specified on the command line."),afterParse:e=>{(0,r.isTrue)(e.exitWhenDone)&&(s.Settings.exitWhenDone.envValue=!0)}}},80338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ForceArg=void 0;const s=i(43414),r=i(38625);t.ForceArg={beforeParse:e=>e.option("--force","Deletes prior cached directory metadata, and forces directory contents to be re-scanned."),afterParse:async e=>{(0,r.isTrue)(e.force)&&(s.Settings.forceSync.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const s=i(55568),r=i(85297),n=i(43414),a=i(38625);function o(){return(0,s.isMainService)()||(0,s.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),s=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":s?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,r.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||s||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},50763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const s=i(23830),r=i(38625);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,r.isFalse)(e.filter)&&(0,s.disableAllFilters)()}}},51315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RebuildArg=void 0;const s=i(43414),r=i(38625);t.RebuildArg={beforeParse:e=>e.option("--rebuild","Rebuild your library by re-importing all your photos and videos (slow!) https://photostructure.com/faq/sync-vs-rebuild/"),afterParse:async e=>{(0,r.isTrue)(e.rebuild)&&(s.Settings.forceRebuildLibrary.envValue=!0)}}},64239:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SkipUpdateArg=void 0;const s=i(43414),r=i(38625);t.SkipUpdateArg={beforeParse:e=>e.option("--skip-updates","DANGEROUS: If you want to immediately import specific files or directories and skip any pending library maintenance tasks (like library rebuilds), use this argument. Note that asset aggregation may be incorrect after using this command if there are updates pending."),afterParse:e=>{(0,r.isTrue)(e.skipUpdates)&&(s.Settings.noModelUpdates.envValue=!0)}}},24709:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(91464),o=i(93125),l=i(43414),u=i(96593),c=i(28033),d=i(61473),h=i(11944),f=i(39938),m=i(61570),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,s.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const r=i[0],n=(0,s.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(r)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...r,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...r]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const s=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=s){t.releasedAt=s;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},69258:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const s=i(4866),r=i(7162),n=i(46852),a=i(43414),o=i(61473),l=i(11944),u=i(26588),c=i(30690),d=i(24709),h=i(51832),f=i(18290),m=i(96672),p=i(82355),g=i(7587),y=i(52465),v=i(40399),w=i(83089),S=(0,s.lazy)((()=>(0,r.mkLogger)("curators.AssetTagger")));async function b({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:s,uris:r}){const u=[];t.some((t=>t.nativePath===e.nativePath))||t.unshift(e),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,g.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),await(0,n.thenMap)((0,f.dateTagFile)(e,s),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,w.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,p.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(r),(e=>{S().debug("file paths for uris",{uris:r,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const b=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(y.normalizeTagRoot),o.joinTagPath)),P=await(0,y.tagDeltas)(i,b);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:b,result:P}),P}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),s=await(i?.posixFile_());if(null==i||null==s)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:s,doNotSend:!0,fatal:!1});const r=e.getShown();r?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:r?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await b({primaryVariation:s,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=b},51832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const s=i(96593),r=i(11254),n=i(11944),a=i(39938);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([r.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,s.readTags)(e))}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const s=i(4866),r=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,s.lazy)((()=>new Intl.DateTimeFormat((0,r.localeSync)(),{month:"short"}))),v=(0,s.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function S(e){return 13-e}function b(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:S(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:b(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=S,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=b,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const s=(0,c.bestCapturedAt)(i);return null==s||(0,c.capturedAtSrcFromStat)(s.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(s.date)}},96672:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const s=i(4866),r=i(7162),n=i(61473),a=i(22356),o=i(11944),l=i(49049),u=i(11254),c=i(89452),d=i(9069),h=i(63216),f=(0,s.lazy)((()=>(0,r.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},82355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(1058),o=i(91464),l=i(2073),u=i(46852),c=i(43414),d=i(96593),h=i(28033),f=i(61473),m=i(11944),p=i(59694),g=i(39938),y=i(43947),v=i(1429),w=i(66776),S=i(11254),b=i(82798),P=i(52465),M=i(83089),_=(0,r.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,r.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,b.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],r=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))r.push(t);else{const e=(0,b.toS)(t).replace(k,(e=>(i.push(e),"")));r.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=r.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,s.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=S.TagRoots.Keywords),e[0]!==S.TagRoots.Keywords&&(p?t.push([S.TagRoots.Keywords,...e]):y&&e.unshift(S.TagRoots.Keywords));for(const e of f)t.push([S.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,r]=(0,s.partition)(x(e),M.isWhoTag),n=(0,v.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...r.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},7587:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const s=i(46852),r=i(43414),n=i(96593),a=i(11254),o=i(11944),l=i(39938),u=i(66776);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(r.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,s.thenMap)((0,n.readTags)(e),c)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const s=i(7162),r=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,s.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...r.Settings.rootTagKeywordsAliases.values,...r.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...r.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...r.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...r.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),s=(0,n.tagDiff)(e,t),a=r.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,s)&&(s.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:s}}},40399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const s=i(4866),r=i(7162),n=i(91464),a=i(46852),o=i(15465),l=i(11944),u=i(39938),c=i(66776),d=i(90957),h=i(11254),f=(0,s.lazy)((()=>(0,r.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,s.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():(0,c.orElse)(m.get(e.trim().toLowerCase()),(()=>(0,n.capitalize)(e)))}t.friendlySubtype=y,t.fixCase=v},83089:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const s=i(4866),r=i(7162),n=i(43414),a=i(96593),o=i(71932),l=i(65308),u=i(61473),c=i(11944),d=i(39938),h=i(1429),f=i(61570),m=i(11254),p=i(39784),g=(0,s.lazy)((()=>(0,r.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),s=i?.peopleNames;(0,c.isNotEmpty)(s)&&t.push(...s)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},18130:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),S=i(76851),b=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),E=i(88491),D=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class A extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),s.add(this),this.schema=e,this.dbFile=t,r.set(this,0),n.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,s,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const s=new C.Migration(this.schema,this.db,t),r=await s.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:r,migration:s,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,r,(e=l(this,r,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,b.isDirSQLiteReadWrite)(e),r=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,s,"m",o).call(this,r),i||await(0,y.dbBackupCold_)(r,e),e.join(this.dbFile.base)}}t.Db=A,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),S=i(9816),b=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),E=i(94332),D=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,s,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,s,"m",a).call(this)}),s.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),r.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,b.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,r,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,s,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,r,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,s,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,r,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,r,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,r=new WeakMap,s=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=b.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,S.isUpdateReadyToInstall)()}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const s=i(4866),r=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),S=i(39938),b=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,s.lazy)((()=>(0,r.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,S.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const s=await f.PosixFile.forUri(i.uri);if(null==s)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(s.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:s,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+s.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:s}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:s}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,S.mapNotBlank)(e,m.toNativePath_));let r,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*b.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(r=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==r||null==o){const i=await(0,n.getLiveDbDir_)(e),s=await i.db.uri_();r=i.useReplica,r&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:s,useReplica:r})}})),null==o||null==r)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();r&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!r),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:r,libraryDbFile:t,libraryDbBackupDir:s,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const s=i(51498),r=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,r.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new s.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const s=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return s.database.open?{sq:i,stmt:s}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:s,stmt:r}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(s));const n=r[i].bind(r);return null==s.bindings?n():n(s.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const s of e){if((0,h.blank)(s)||s.trim().startsWith("--"))continue;this.run({sql:s});const e=(0,m.replaceAll)((0,m.ellipsize)(s,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const s=i(10408),r=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,r.blank)(e)){t._dbSetupErrors.add((0,s.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const s=i(4866),r=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,s.lazy)((()=>(0,r.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const s=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),r=(0,o.compactBlanks)(s.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=s[0],l=s.slice(1),u=n?.id;if((0,o.isEmpty)(r)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:r,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,r[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:r});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),s=(0,a.joinTagPath)([...f,...i]);t._path!==s&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:s}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:s}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:s}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:s}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(s).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const r=s(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,r.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var s,r,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),S=i(98250),b=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),E=i(43947),D=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),A=i(72537);t.Migration=class{constructor(e,t,i){s.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=S.PosixFile.for(b.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,s,"m",r).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),r=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(r);return o?await r.bind(I.Migrations)(this.db):await a(this,s,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},s=new WeakSet,r=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const s of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+s.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(s))),await(0,h.thenOrTimeout)(this.applyMigration_(s,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+s.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(s.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,A.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),S=i(66776),b=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),E=i(85476),D=(0,r.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,S.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,S.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,s]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,b.toInt)(e)));return(0,p.validYMD)(t,i,s)?new Date(t,i-1,s):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,b.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,b.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const r of t){const t=(0,_.toS)(r.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,s.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,s.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),s=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:s});for(const t of s)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const s=i(70403),r=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),S=i(53719),b=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),E=i(6314),D=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),A=i(9069),O=i(70582),L=(0,r.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const s=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(s,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(s)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,O.withDbSync)(e,z,(0,S.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const r=await(0,y.sqliteNativePath_)(),n=await(0,s.thenElapsed)((0,a.stdout_)(r,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,b.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,A.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:s=w.Settings.dbWalCheckpointType.valueOrDefault}){if((s=l.CheckpointTypes.getCI(s)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const r="wal_checkpoint("+s+")",[n]=(0,F.toA)(t.pragma(r));return L().info("checkpoint()",{pragma:r,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),s=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${s})`);try{const e=await(0,y.sqliteNativePath_)(),r=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},r),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:r});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[s.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:r});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${s}.`),V(s),L().info(`repairDbFile_(): ${s} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(s),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const s=i(13779),r=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,s.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,r.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const s=i(39938),r=i(89253);function n(e){const t=new r.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,s.blank)(i.name)||(0,s.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const s=i(5853),r=i(43414),n=i(82798);t.withDbSync=function(e,t,i=r.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,s.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=r.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,s.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},30690:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),S=i(84418),b=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),E=i(87748),D=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),A=i(89452),O=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),s.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),s=await(0,w.readTags)(i),r=await(i?.mtimeMs());null!=i&&null!=s&&null!=r&&e.push({...s,SourceFile:i.nativePath,sourceModifiedTime:r,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?r.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?r.ops().firstf((t=>r.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??r.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return r.ops().count(r.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const s=(0,d.mkLogger)("Asset("+e+").remove()"),n=r.ops().findById(e);if(null==n)return void s.warn("asset not found");const a=n.isActive(),o=n.tagIds();s.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=A.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),A.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),r.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await r.deletePreviews(e)}catch(e){s.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,r,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,r,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,r,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=r.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),A.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),r.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,O.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,b.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const s=this.getAssetFiles().find((e=>e.uri===i));if(null!=s)return s;const r=new A.AssetFile;return this.addAssetFile(r),!0!==t?.skipUpsert?await r.upsertIfNeeded_(e):await r.setFile_(e),r}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=r.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),s=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:s})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,b.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),s=(0,b.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,b.isEmpty)(i)&&(0,b.isEmpty)(s))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,b.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,b.isEmpty)(s)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",s).andWhere({assetId:this.id}).delete())),this.tags=void 0;const r=(0,b.uniq)([...t,...i]).filter((e=>!s.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(r,1),r}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,b.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=r.dbl.all(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(A.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof A.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const s=t.id===e.id||t.uri===e.uri;return s&&(this.assetFiles[i]=e),s})));const i=e instanceof A.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const s=Date.now();A.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:s}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const r=A.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:s}).where({id:i})));1!==r.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:r});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const s=e.ap(this.id);await(0,m.thenMap)(s.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await s.posterLink())}));const r=!0;this.imgAttrs.set(t,await s.imgAttrs(t,r,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(A.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new A.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,r=W,s=new WeakSet,n=function(){return r.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=r.dbl.first(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=r.dbl.first(r.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),S=i(3955),b=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),E=i(65642),D=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),A=i(11944),O=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Q=i(30690),Y=i(13222),Z=i(50725),X=i(1724);class ee extends X.TimestampedModel{constructor(){super(...arguments),s.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,Y.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>b.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,A.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Q.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Q.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const s=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",s).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,S.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,s,"m",r).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,q.assignAllFields)(this,(0,q.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,s,"m",r).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Q.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const s=await e.uriObject_();return null==s?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(s),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const s=e.ap(this.assetId),r=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>r.push(e))),this.isVideo)return r;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return r;const n=(0,A.compact)(await Promise.all([...await s.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return r.push(...(0,A.uniqBy)(n,(e=>e.size))),r}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,s=x.URI.parse(this.uri),r=await t.exists();if(null==e||(0,A.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:r};function n(){return(0,O.at)((0,O.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=s.scheme===G.PS_LIBRARY_SCHEME,l=o?s.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,O.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(s.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:r}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,s=new WeakSet,r=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const s=i(80294),r=i(75556);t.toAssetId=function(e){const t=(0,r.toGt0)(e?.assetId)??(0,r.toGt0)(e?.id);if(null==e||null==t||!(0,r.isNumber)(e?.capturedAtLocal))return;const i=((0,r.toGt0)(e.v)??(0,r.toGt0)(e.updateCount)??(0,r.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,r.gt0)(e.durationMs)&&(n.durationHMS=(0,s.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const s=i(87748),r=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,s.stringify)(e.priorValue),_newValueJson:(0,s.stringify)(e.newValue)}))))}get priorValue(){return(0,r.parseJSON)(this._priorValueJson)}get newValue(){return(0,r.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const s=i(7907);class r extends s.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=r,r.$tableName="AssetTag",r.$uniqueColumnName="assetId,tagId",r.$useCache=!1,r.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const s=i(4866),r=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,s.lazy)((()=>(0,r.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const s=i(4866),r=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,s.lazy)((()=>(0,r.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,s.lazy)((()=>(0,r.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var s;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const r=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[r.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const s=this[e];return null===s?[e,null]:!(0,f.isPrimitive)(s)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(s)]:[e,s]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:s}){const r=this.class(),n=(0,l.notEmptyOr)(s,r.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:r.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,s=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(s.$schema+"."+s.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const s=i(62936),r=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,r.libraryDataDirPosixFile)(e),(e=>(0,s.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const s=i(7162),r=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const s=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,r.includes)(s.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const s=new i;return null==t?s:d(s,t,(0,r.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,r){if(null!=t)return Array.isArray(t)?t.map(((t,s)=>e(t,i,`${r}[${s}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,s.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:r,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),S=i(79015),b=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),E=i(1429),D=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),A=i(79563);t.ModelOps=class{constructor(e,t){s.add(this),this.model=e,this.db=t,r.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,r,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,A.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,S.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,S.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,s,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const s of e){const e=this.$cachedById(s);null!=e?t.push(e):i.push(s)}const s=(0,f.batches)(i,b.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(s))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,r,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,s,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,s,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),s=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?s.push("DO NOTHING"):s.push("DO UPDATE SET",i),s.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const s=e[i];if(null==s)return;t[i]=s}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,s,"m",u).call(this,e),r=this.findOneBy(t);return h(this,s,"m",l).call(this,i,r),i!==e&&h(this,s,"m",l).call(this,e,i),i}h(this,r,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),r=[];for(const n of(0,f.batches)((0,F.toA)(e),b.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,s,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,s]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(s,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),r.push(e)}}return r}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=b.Settings.dbBatchSelectSize.valueOrDefault;let i,s;do{i=this.allf((i=>(i=e.qb(i),null!=s&&(i=i.andWhere("id",">",s)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(s=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,s,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const r={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(r);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,s,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const s=i(4691),r=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,r.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void c().debug("applyOnce(): already done",{priorCompleted:r});const n=this.ops().insertOne(e),o=await t(n);return(0,s.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const s=i(70612),r=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),S=i(79563),b=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),s=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(s),D.ops().delete(i)}static minCreatedAt(){const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:r.pid,hostname:(0,s.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,S.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const s=i(84253),r=i(1724);t.ProgressMetaNames=(0,s.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends r.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const s=i(4866),r=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,s.lazy)((()=>(0,r.mkLogger)("model.ShaBlocklist"))),f=(0,s.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,s.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,s.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),S=i(24603),b=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),E=i(39784),D=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),A=i(14405),O=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:s.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of s.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,S.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return s.incrAssetCount(s.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||s.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return s.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=s.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});s.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?s.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?s.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return s.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new s;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,s,"m",r).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,b.map)(a,(e=>i.parentId=e.id)),s.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){s.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,r=s.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:r});try{if(null==r)s.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=r._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:r.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...r.path,e.name]),!1);s.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:r.id}))),this.delete()}}finally{t&&s.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return s.orderBy(s.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,b.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=s.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=s.ops().all(t);for(const e of i)s.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:s.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=s.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:s.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(A.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?s.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):s.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let s=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return s=s.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?s.orderByRaw(`ABS(Asset.id-${e.id})`):s.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,s,r]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(A.toAssetId))));for(const t of s)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(s)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,b.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(A.toAssetId));return this.logger().debug(this.path+": Found "+s.length+" related assets"),s}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,s=z,r=function(e){const t=new s;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new s;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=s.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>s.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{s._upsertDefaultRoots();const e=s.ops().all(s.orderBy(s.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],s.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const s=i(62936),r=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,r.tag_fts_root)(e._path),path:(0,r.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(s.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const r=c.$tableName;this.dbl.runScript([`INSERT INTO ${r}(${r}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const s=i(13779),r=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,s){this.tags=e,this.before=t,this.after=i,this.limit=s,this.logger=()=>(0,r.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,s.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,s.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,s.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],r=e.filter((e=>e.length>5));for(const e of r){const r=(0,s.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==r?i.push(e):r.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const s=i(70283),r=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,r.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,s.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,s.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},80796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeApplyDeleted=t.maybeApplyExcluded=void 0;const s=i(7162),r=i(99869),n=i(10408),a=i(17875),o=i(79141),l=i(11944),u=i(39938),c=i(87748),d=i(75556),h=i(2934),f=i(17078),m=i(42313),p=i(30690),g=i(89452),y=i(36310),v=i(65548),w=(0,s.mkLogger)("ops.ApplyExcluded");async function S(e,t){const i=v.Progress.insertNew(t?{uri:m.EmptyDeletedURI,state:"processing",volume:"๐Ÿ—‘๏ธ",scanningPct:0,hed:"Removing deleted assets from library and disk"}:{uri:m.EmptyRemovedURI,state:"processing",volume:"โ๏ธ",scanningPct:0,hed:"Removing excluded assets from library"}),{assetCount:s,assetFileCount:y}=(0,h.parseJSON)(e.value);(0,d.gt0)(s)&&(0,d.gt0)(y)||w.throw("Refusing to "+e.name+": invalid model counts",{op:e});const S=t?"deletedAt":"excludedAt",b=t=>t.where("Asset.shown",0).andWhere("Asset."+S,e.createdAt),P=p.Asset.dbl.pluckAllf((e=>b(e.select("Asset.id"))));if(P.length>s&&w.throw("Refusing to "+e.name+": too many assets!",{op:e,assetCount:P.length}),t){const t=g.AssetFile.dbl.pluckFirstf((e=>b(e.countDistinct("AssetFile.id").join("Asset","Asset.id","AssetFile.assetId"))));t>y&&w.throw("Refusing to "+e.name+": too many impacted files!",{op:e,dbAssetFileCount:t})}const M=[];function _(e){const i=P.length,s=[`Removed ${(0,f.plur)(i,"asset")} from your library.`+(e>=i?"":` ${(0,f.plur)(i-e,"asset")} need to be removed.`)];if(t){const e=(0,l.count)(M,(e=>e.unlinked));s.push((0,f.plur)(e,"file")+" deleted from disk."),(0,l.count)(M,(e=>!e.unlinked))>0&&s.push((0,f.plur)(e,"file")+" could not be deleted from disk. Check the logs for details.")}return s}const T=(0,r.rateLimited)({name:"applyRemovable",f:async e=>{e<0||(i.completePct=(0,d.clamp)(0,100,Math.round(e/P.length)),i.incompletePct=(0,d.clamp)(0,100,100-i.completePct),i.dek=_(e),i.upsert())},minCallDelayMs:500});w.info("applying...",{op:e,assetIds:P});try{for(const e of P){const i=await p.Asset.remove({assetId:e,blocklistShas:!0,unlinkAssetFiles:t});M.push(...i?.deletedMeta.filter((e=>(0,u.notBlank)(e.nativePath)))),await T(P.indexOf(e))}e.upsert({completedAt:Date.now()}),i.hed=t?"Emptied trash.":"Excluded assets removed.",i.dek=_(P.length),i.state="done",i.completedAt=Date.now(),i.upsert(),w.info("Complete!",{op:e})}catch(t){const s=(0,o.toWrappedError)("Could not apply "+(0,c.stringify)(e),{cause:t});(0,a.onError)(s),i.upsert({hed:"Failed: "+(0,n.errorToS)(s),state:"done",completedAt:Date.now()})}}t.maybeApplyExcluded=async function(){return y.Operation.applyIfPending({name:"applyExcluded"},(e=>S(e,!1)))},t.maybeApplyDeleted=async function(){return y.Operation.applyIfPending({name:"applyDeleted"},(e=>S(e,!0)))}},83148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPendingOperations=void 0;const s=i(80796);t.checkPendingOperations=async function(){await(0,s.maybeApplyExcluded)(),await(0,s.maybeApplyDeleted)()}},35735:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Queue=t.assetUpdatesQueueName2uri=t.assetUpdatesUri2QueueName=t.assetFileUpdatesQueueName2uri=t.assetFileUpdatesUri2QueueName=void 0;const s=i(46852),r=i(93813),n=i(91464),a=i(87130),o=i(96781);function l(e){return`assetFileUpdates:${r.AssetFileVersion}:${e}`}function u(e){return`assetUpdates:${r.AssetVersion}:${e}`}t.assetFileUpdatesUri2QueueName=l,t.assetFileUpdatesQueueName2uri=function(e){return(0,n.stripPrefix)(e,l(""))},t.assetUpdatesUri2QueueName=u,t.assetUpdatesQueueName2uri=function(e){return(0,n.stripPrefix)(e,u(""))};class c extends o.StatsModel{static itemCountForQueues(e){return(0,s.thenOrElse)(a.QueueItem.dbl.pluckFirstf((t=>t.countDistinct("QueueItem.id").join("Queue","Queue.id","QueueItem.queueId").whereIn("Queue.name",e))),(()=>0))}static truncate(){a.QueueItem.dbl.runf((e=>e.delete())),c.dbl.runf((e=>e.delete()))}items(){return a.QueueItem.ops().allf((e=>e.where({queueId:this.id})))}itemCount(){return a.QueueItem.dbl.pluckFirstf((e=>e.where({queueId:this.id}).count()))}upsertWorkItems(e){return a.QueueItem.ops().upsert(e.map((e=>({queueId:this.id,...e}))))}}t.Queue=c,c.$tableName="Queue",c.$uniqueColumnName="name"},87130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueueItem=void 0;const s=i(96781);class r extends s.StatsModel{eql(e){return null!=e&&(null!=this.id&&this.id===e.id||this.contents===e.contents&&this.queueId===e.queueId)}}t.QueueItem=r,r.$tableName="QueueItem",r.$uniqueColumnName="queueId,contents"},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const s=i(4866);t.statsDb=(0,s.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const s=i(19658),r=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,r.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:s.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},96781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatsModel=void 0;const s=i(7907),r=i(81520);class n extends s.Model{}t.StatsModel=n,n.$schema="stats",n.db=r.statsDb},16630:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const o=i(4866),l=i(7162),u=i(67654),c=i(46852),d=i(7383),h=i(39506),f=i(53525),m=i(98250),p=i(72461),g=i(31216),y=i(47874),v=i(43414),w=i(96593),S=i(11944),b=i(59694),P=i(39938),M=i(88491),_=i(66776),T=i(75556),E=i(30690),D=i(89452);t.isFileInSync=async function(e){return new x(m.PosixFile.for(e)).alreadySynced()};const k=new h.SerialLaterQueue;class x{constructor(e,t){this.file=e,s.set(this,void 0),r.set(this,new Set),this.alreadySynced=(0,d.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>a(this,s,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,d.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?a(this,s,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,o.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,o.lazy)((()=>v.Settings.useImageHashes.valueOrDefault?(0,p.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,o.lazy)((()=>(0,c.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,o.lazy)((async()=>{const e=await this.capturedAt_();return a(this,s,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,d.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,P.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return a(this,s,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return a(this,s,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new E.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,d.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,g.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtOrImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,d.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return a(this,s,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;a(this,s,"f").debug("apply(): "+t+": returned null")}catch(e){throw a(this,s,"f").debug("apply(): "+t+" rejected: "+e),e}})),n(this,s,(0,l.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f"),this.ctx=(0,y.forceContextOrSetting)(t)}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),a(this,s,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}a(this,s,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(){const e=await this.file.uri_();if(null!=e)return D.AssetFile.ops().findOneBy({uri:e})??D.AssetFile.ops().findOneBy({uri:this.file.fileuri()});a(this,s,"f").warn("byUri() uri is null",{file:this.file})}assetByNormalizedPathUri(){return(0,c.thenMap)(this.file.normalizedPathUri_(),(e=>E.Asset.findFirstByFile((t=>t.where("AssetFile.uri",e)))))}assetBySha(){return(0,c.thenMap)(this.file.sha(),(e=>E.Asset.findFirstByFile((t=>t.where("AssetFile.sha",e)))))}async assetByCapturedAtOrImageHash(){const e=await this.capturedAt_();if(null==e)return a(this,s,"f").throw("Cannot import, capturedAt is null"+f.InternalErrorFlag);if(v.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=v.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,T.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},r=Math.max(M.secondMs,v.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,d.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:r});if(null==t)a(this,s,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:r});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(v.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void a(this,s,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const n=await this.dominantLabhashes();if((0,S.isNotEmpty)(n)){const t=e.localBoundaries({delta:4*r});if(null==t)a(this,s,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:r});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",n).orWhereIn("mode1",n).orWhereIn("mode2",n))));if(null!=e)return e}}return this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash))}))}async firstSimilarAssetByQuery(e,t){a(this,r,"f").size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(a(this,r,"f"))));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&a(this,s,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const n=(0,b.sortBy)(e.filter((e=>!a(this,r,"f").has(e.id))),(e=>[(0,_.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of n)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const n=(0,u.whyNotSameAsset)(t,e,i);if(null==n)return a(this,s,"f").info("Found sibling AssetFile",e),E.Asset.ops().findById(e.assetId);a(this,r,"f").add(e.id),a(this,s,"f").debug("Contemporary assetFile not similar: "+n,e?.uri)}}}t.AssetFileFinder=x,s=new WeakMap,r=new WeakMap},93898:function(e,t,i){"use strict";var s,r,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult=void 0;const u=i(4866),c=i(7162),d=i(78342),h=i(53525),f=i(87489),m=i(23872),p=i(24948),g=i(31216),y=i(47874),v=i(11944),w=i(39938),S=i(38625),b=i(39784),P=i(49374),M=i(93445),_=i(16630),T=i(50100);t.importFileToResult=async function(e,t){const i=P.Library.instanceRequired();return(0,p.syncReport)().wrap_({path:e.nativePath,from:"importFileToResult()",fn_:()=>new E(e,i.assetFileRepository(),t).apply_()})};class E{constructor(e,t,i){s.add(this),this.file=e,this.repo=t,this.start=Date.now(),r.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else{const t=await(0,m.whyRejectFile)(this.file,(0,M.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,r,"f").throwIfAborted();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i){l(this,r,"f").info("Deleting prior AssetFile, and requesting prior asset repair",{rejected:e,prior:i}),i.delete();const t={assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)};(0,f.submitTask_)("repairAsset",t)}if(l(this,r,"f").throwIfAborted(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,w.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,r,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,r,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,r,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,s,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,r,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new _.AssetFileFinder(e,i),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=E,r=new WeakMap,n=new WeakMap,s=new WeakSet,a=async function(){l(this,r,"f").throwIfAborted();const e=await this.whyRejected();if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,r,"f").throwIfAborted();const t=await this.prior();if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,r,"f").throwIfAborted();const i=await this.assetFile_();if(null==i)return l(this,r,"f").throw("_apply(): unexpected null assetFile");const s=i.id;if(null==s)return l(this,r,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,r,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,r,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;l(this,r,"f").throwIfAborted();try{o=await(0,T.assetPostUpsertTasks_)(a,this.ctx)}catch(e){e instanceof d.AbortError?l(this,r,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,r,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:s,assetFile:i,asset:a,uri:n,uris:[n,...(0,b.toA)(o?.newAssetFileUris)]}}},97840:function(e,t,i){"use strict";var s,r,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),S=i(35280),b=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){s.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,b.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,s,"m",r).call(this,e);return null!=t&&(await l(this,s,"m",n).call(this,e,t),await l(this,s,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),r=await e.posixFile_();null==r&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(r);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,s,"m",n).call(this,r,e),h=null!=await l(this,s,"m",o).call(this,r,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,b.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:r.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,S.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(r);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===r.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+r.nativePath,elapsedMs:Date.now()-i,url:(0,S.mkAssetUrl)(a.id)?.toString()}),f}},s=new WeakSet,r=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const s=this.originalsDir.join(...i),r=await this.findLibraryFileWithSameContents(e,s);if(null!=r)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:r}),r;const n=await s.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:s}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),r=[];for(const e of i)r.push(await l(this,s,"m",a).call(this,e,t));return(0,b.compact)(r)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},50100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const s=i(7162),r=i(92356),n=i(78342),a=i(5685),o=i(79141),l=i(19371),u=i(46517),c=i(11944),d=i(43383),h=i(75556),f=i(49374),m=i(69258),p=i(30690),g=i(97840),y=i(55903),v=(0,d.defer)((()=>(0,s.mkLogger)("sync-file.AssetPostUpsertTasks"))),w=(0,d.defer)((()=>new a.LastOneInWins("Asset tasks")));function S(e,t){const i=v().addContext(`.postUpsertAssetTasks_(Asset:${e?.id})`);if(t.skipPreviews&&t.skipAssetTagging)return void i.info("skipped (skipPreviews && skipAssetTagging)");if(null==e)return i.throw("unexpected null asset",{asset:e});const s=e.id;return null==s?i.throw("unexpected null asset.id",{asset:e}):w().enqueue(s,(async s=>{try{return async function(e,t,i,s){const n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted(s),(0,c.isEmpty)(a)&&(await p.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,g.mayCopyAssetsToLibrary)()){const t=f.Library.instanceRequired().assetFileRepository();for(const r of a){e.throwIfAborted(s);try{if(await r.exists()){const e=await t.maybeCopyToLibrary_(r,i);null!=e&&o.newAssetFileUris.push(e.uri)}}catch(t){e.warn("Failed to copy variation to library, but we'll try to continue",{af:r,error:t})}}}const d=i.skipPreviews?void 0:await(0,y.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...i,ac:s}),w=await async function(e,t){if((0,h.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?v().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,r.bestExistingAssetFile)(e.getAssetFiles())}(t,d);if(null==w)return e.throw("null primaryOrShownAssetFile_()",{asset:t});if(t.markShownAndUpsert_(w),i.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,m.tagAndUpsertAsset_)(t),!0!==i.skipPreviews&&t.isVideo()){const s=await(t.getShown()?.posixFile_());if(null==s)return e.throw("null asset.getShown().posixFile",{asset:t});o.transcoded=null!=await(0,u.transcode_)(s,l.Previews.instance().ap(n).mp4(),{force:i.forceRebuildPreviews})}return o}(i,e,t,s.signal)}catch(t){if(t instanceof n.AbortError)return void i.warn("aborted, next caller will clean up my mess",{error:t});const s=[t];i.error("failed, marking asset unshown",{error:t});try{e.markUnshownAndUpsert()}catch(e){i.error("failed to mark asset unshown",{upsertError:e}),s.push(e)}throw new o.WrappedError("Failed to post-process assset "+e.id,{causes:s})}}))}t.assetPostUpsertTasks=function(e,t){try{return S(e,t)}catch(e){if(e instanceof n.AbortError)return void v().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=S},91877:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuccessResult=t.isErrorResult=t.isImportResult=void 0;const s=i(24948),r=i(39938),n=i(75556);function a(e){return null!=e&&(0,r.notBlank)(e.path)&&s.SyncFileStates.has(e.state)}function o(e){return(0,r.notBlank)(e.error)||e.state===s.SyncFileStates.failed}t.isImportResult=a,t.isErrorResult=o,t.isSuccessResult=function(e){return null!=e&&!o(e)&&(0,n.gt0)(e.assetId)&&(0,n.gt0)(e.assetFileId)&&a(e)}},5848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset=void 0;const s=i(13779),r=i(7162),n=i(93813),a=i(46080),o=i(67654),l=i(92356),u=i(46852),c=i(6667),d=i(47874),h=i(43414),f=i(11944),m=i(39938),p=i(38625),g=i(24603),y=i(30690),v=i(89452),w=i(50100),S=i(84249);async function b(e){const[t,i]=(0,s.partition)(e,(e=>e.isVersionUpToDate()));for(const e of i){const i=t.find((t=>t.sha===e.sha));if(null!=i){(0,r.mkLogger)("UpdateAsset("+e.assetId+")").info("backfilling",{sibling:i,dest:e});const t=await e.updateFromShaSibling_(i);null!=t&&t.upsert()}}}t.updateAsset=async function(e){try{const t=await async function(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,s=(0,r.mkLogger)(`sync-file.UpdateAsset(${i})`),P=y.Asset.ops().findById(i);if(null==P)return s.throw("no such asset");const M=P.$clone(),_=P.getShown()?.$clone();(await(0,u.mapAsync)({name:"UpdateAsset.updateAssetFile",arr:P.getAssetFiles(),f:e=>(0,S._updateAssetFile_)({ctx:t,assetFileId:e.id,af:e})})).some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&P.clear(),await b(P.getAssetFiles());const T=(0,l.sortAssetFiles)(P.getAssetFiles()),E=T?.[0];if(null==T||null==E)return s.warn("No existing files. Skipping for now."),P.markUnshownAndUpsert(),{asset:P,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!E.isVersionUpToDate())return s.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:E}),P.markUnshownAndUpsert(),{asset:P,rejected:`Best AssetFile:${E.id}, could not be updated. Un-showing Asset:${i}`};const D=await E.capturedAt();if(null==D)return s.warn("Best file failed to extract a captured-at",{bestAcceptedAF:E}),P.markUnshownAndUpsert(),{asset:P,rejected:`Best AssetFile:${E.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const k=new Set,[x,C]=await(0,u.partitionAsync)(T,(e=>(0,o.isSimilarAssetFile)(e,E)));if((0,f.isNotEmpty)(C)){const e=await(0,a.aggregateAssetFiles)(C);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});k.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),s.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function F(e){return(0,f.uniq)(x.map((t=>t[e])))}const I=await Promise.all(x.map((e=>e.capturedAt()))),A=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,O=I.map((e=>e?.localBoundaries({delta:A}))),L=(0,c.min)(O.map((e=>e?.start)))??D.localBoundaries({delta:A})?.start,R=(0,c.max)(O.map((e=>e?.end)))??D.localBoundaries({delta:A})?.end,N=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${E.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",F("sha")),null==L||null==R?s.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:L,endBoundary:R}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[L,R]),e.orWhereIn("AssetFile.meanHash",F("meanHash")).orWhereIn("AssetFile.diffHash",F("diffHash")).orWhereIn("AssetFile.dctHash",F("dctHash"))))));s.info("asset file candidates for adoption: ",N.map((e=>e.posixPathFromGrandparent)));const B=[];for(const e of N)try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,E)&&(s.info("adopting similar asset file",{af:e}),k.add(e.assetId),e.shown=!1,P.addAssetFile(e),e.upsert(),B.push(e))}catch(t){s.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}s.info("fetched expansion",{retainAFs:x.map((e=>e.id)),rejectAFs:C.map((e=>e.id)),externalAssetFiles:N.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:B.map((e=>e.posixPathFromGrandparent))}),await b([...x,...B]),t.skipPreviews&&t.skipAssetTagging?(s.info("skipping previews and tagging",t),P.upsert()):await(0,w.assetPostUpsertTasks_)(P,t);const j=!(0,g.eql)(M,P),z=!(0,g.eql)(_,P.getShown()),V=!(j||z||t.forceRebuildPreviews||t.forceSync);return s.tap({msg:"updateAsset() result",level:"info",result:{asset:P,assetIdsToUpdate:Array.from(k),assetFiles:P.assetFiles,skipped:V},meta:{ctx:t,assetChanged:j,primaryAssetFileChanged:z}})}(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}}},84249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t._updateAssetFile_=t.updateAssetFile=void 0;const s=i(92356),r=i(10408),n=i(7162),a=i(47874),o=i(25116),l=i(11944),u=i(39938),c=i(61570),d=i(30690),h=i(89452);async function f({ctx:e,assetFileId:t,af:i}){const s=(0,n.mkLogger)(`updateAssetFile(${t})`),r=await(i?.posixFile_()),a={id:t,assetFileId:t,path:r?.nativePath,uri:i?.uri};if(null==i)return{...a,error:"db record not found"};if(null==r)return{...a,error:"file for URI not found"};const l=await(r?.isDeletedUri(i.uri));if(null==l)return s.info("no-op: file URI points to an unmounted volume",a),{...a,skipped:!0};const c=await i.whyRejected();if(l||!(0,u.blank)(c)){const e={...a,rejected:c,deleted:l};return s.warn("file was deleted or rejected. Deleting.",e),i.delete(),e}const d=await r.uri_();if(!await(0,o.uriIsEquivalent)(d,i.uri)){const t=await m(i,d,e.forceSync);if(null!=t)return{...a,...t}}return!e.forceSync&&await i.matchesFile()?(s.info("no-op: file already matches db record",a),i.touch(),{...a,skipped:!0}):{...a,...await p(i,e.forceSync)}}async function m(e,t,i){const r=(0,n.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,l.uniq)([...(0,o.uriEncodingVariants)(e.uri),...(0,o.uriEncodingVariants)(t)]);r.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const u=h.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,l.isNotEmpty)(u)){r.warn("Found other AssetFiles with equivalent URIs.",{afIds:u.map((e=>e.id))});const t=[e,...u],n=(0,s.sortAssetFiles)(t);if((0,l.isEmpty)(n))return r.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,c.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const o=t.map((e=>e.id));for(const e of n)if(await e.exists()){h.AssetFile.dbl.runf((t=>t.whereIn("id",o.filter((t=>t!==e.id))).delete()));const s=p(e,i);return d.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,l.uniq)(t.map((e=>e.assetId)))))),s}}r.info("no-op, no duplicate URIs.")}async function p(e,t){return null!=await e.upsertIfNeeded_(void 0,t)&&d.Asset.touch([e.assetId]),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await f({ctx:(0,a.forceContextOrSetting)(e),assetFileId:e.assetFileId,af:h.AssetFile.ops().findById(e.assetFileId)})}catch(t){return{id:e.assetFileId,...e,error:(0,r.errorToS)(t)}}},t._updateAssetFile_=f,t.handleAssetFileUriChange=m,t.updateAssetFileIfNeeded=p},55903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const s=i(53525),r=i(19371),n=i(7162),a=i(47874),o=i(25116),l=i(11944),u=i(43383),c=i(24603),d=i(75556),h=i(61570),f=i(39784),m=i(30690),p=(0,u.defer)((()=>(0,n.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,f.toA)(e.assetFiles).find((e=>(0,d.gt0)(e.assetId)))?.assetId,i=(0,a.forceContextOrSetting)(e),n=p().addContext(".Asset:"+t);if(i.skipPreviews)return void n.warn("skipPreviews is true: no-op");if(!(0,d.gt0)(t))return n.throw("invalid assetId",{assetId:t});const u=e.asset??m.Asset.ops().findById(t);if(null==u)return n.throw("Asset:"+t+" not found");n.throwIfAborted(e.ac);try{const a=await u.getExistingAssetFiles();if((0,l.isEmpty)(a))return void n.warn("no existing assetFiles",{asset:u});const d=r.Previews.instance().ap(t),f=await d.readInfo();n.throwIfAborted(e.ac);const m=await(0,r.buildAssetPreviews_)({...i,assetId:t,assetFiles:a}),p=a.find((e=>e.id===m?.assetFileId))??a.find((e=>(0,o.uriIsEquivalent)(m?.uri,e.uri)));n.info("buildAssetPreviews_()",{result:m,primaryAssetFile:p});const g=await(p?.posixFile_());if(null==p||null==g||!0!==await(g?.exists()))return n.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:m,assetFiles:a.map((e=>(0,h.pick)(e,"id","uri"))),primaryAssetFile:p,primaryPosixFile:g});const y=(0,c.eql)(f,m),v=null==m||y;return{...m,noop:v}}catch(e){throw n.warn("Failed to update previews. Un-showing asset "+t,{error:e}),u.markUnshownAndUpsert(),e}}},12474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateSuccessResult=t.isUpdateErrorResult=void 0;const s=i(39938),r=i(75556);t.isUpdateErrorResult=function(e){return null!=e&&(0,s.notBlank)(e.error)},t.isUpdateSuccessResult=function(e){return null!=e&&(0,r.gt0)(e.id)&&(0,s.blank)(e.error)}},24940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleUpdateCommand=t.describeUpdateCommand=t.UpdateTask=t.validUpdateCommandOrElse=void 0;const s=i(5712),r=i(79378),n=i(4866),a=i(7162),o=i(7383),l=i(49379),u=i(43414),c=i(11944),d=i(87748),h=i(75556),f=i(82798),m=i(91877),p=i(5848),g=i(84249),y=i(12474),v=(0,n.lazy)((()=>(0,a.mkLogger)("sync-file.UpdateTask")));function w(e){return(0,h.gt0)(e.assetId??e.assetFileId)||v().throw("validUpdateCommand(): missing asset or assetFile id",{fatal:!1,retriable:!1,cmd:e}),e}t.validUpdateCommandOrElse=w;class S extends s.Task{constructor(e){super((0,d.stringify)(w(e)),(e=>this.parse(e))),this.cmd=e,this.name=`UpdateTask(${(0,d.stringify)(e)})`}toString(){return this.name}parse(e){for(const t of(0,c.compactBlanks)((0,f.toS)(e).split("\n")).reverse()){const e=(0,r.parseJSON)(t);if((0,y.isUpdateSuccessResult)(e))return e}return v().throw(this.name+".parse() failed",{input:e})}}function b(e){const t=e;return(0,h.gt0)(t.assetId)?"updateAsset:"+t.assetId:(0,h.gt0)(t.assetFileId)?"updateAssetFile:"+t.assetFileId:(0,h.gt0)(t.assetPreviewId)?"updateAssetPreviews:"+t.assetPreviewId:"invalid command: "+(0,d.stringify)(e)}t.UpdateTask=S,t.describeUpdateCommand=b,t.handleUpdateCommand=function e(t){v().info("handleUpdateCommand()",{cmd:t});const i=t,s=(0,o.time)("sync-file."+b(t),(0,h.gt0)(i.assetId)?(0,p.updateAsset)(i):(0,h.gt0)(i.assetFileId)?(0,g.updateAssetFile)(i):v().throw("Invalid update command "+(0,d.stringify)(t)));if((0,m.isErrorResult)(s)){const i=u.Settings.maxRetries.valueOrDefault,r=(0,l.isNonRetriableError)(s.error);if((0,h.gt0)(i)&&(0,h.gt0)(t.retries)&&!0!==r)return v().warn("Retrying failed command",{cmd:t,result:s}),e({...t,retries:(t.retries??u.Settings.maxRetries.valueOrDefault)-1});v().warn("Command failed, and cannot retry",{result:s,isNonRetriable:r,retries:t.retries,maxRetries:i})}return s}},54620:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const s=i(37980),r=i(64063),n=i(9972),a=i(37445),o=i(51053),l=i(43414),u=i(7127),c=i(26367),d=i(78877),h=i(80338),f=i(92045),m=i(50763),p=i(51315),g=i(64239),y=i(90339);!async function(){if(o.isElectron)new y.SyncService;else{const e=await new s.CLI(u.ServiceNames.sync,"[files-or-directories...]","If paths are provided on the command line, they should be fully-qualified.\n\n* Paths to directories will be scanned recursively.\n* Paths to files will be imported if they pass configured filters.\n\nNote that sync will spawn 1 or more `worker` processes to work in parallel.").add(p.RebuildArg,h.ForceArg,n.TimingArg,c.DropWorkQueuesArg,m.NoFilterArg,g.SkipUpdateArg,d.ExitWhenDoneArg,a.WriteSettingsArg,f.LogArgs,r.ColorArgs).parse();l.Settings.argvScanPaths.envValue=e.args,new y.SyncService}}()},28688:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileQueue=void 0;const s=i(13779),r=i(70259),n=i(7383),a=i(87489),o=i(98462),l=i(95725),u=i(24948),c=i(69060),d=i(7162),h=i(6667),f=i(43414),m=i(63526),p=i(35280),g=i(11944),y=i(39938),v=i(38625),w=i(82798),S=i(49049),b=i(89452),P=i(87130),M=i(9497),_=i(38791);class T{static async for(e,t){return new T((0,l.toNativePath_)(e),t)}constructor(e,t){this.logger=(0,d.mkLogger)("AssetFileQueue"),this.fileListener=async e=>{const t=e.map((e=>(0,l.isSimpleFile)(e)?e:o.BaseFile.for(e)));if(this.logger.debug("fileListener()",t),f.Settings.forceSync.valueOrDefault)return this.enqueueSimpleFiles(t);{const e=!0,{fresh:i,stale:s}=await(0,n.time)("sync.precheckFiles",(()=>(0,_.precheckFiles)(t,e)));return this.logger.debug("fileListener()",{fresh:i,stale:s}),this.enqueueSimpleFiles(s)}},this.imgQueue=M.WorkQueue.mk({queueNames:["img:"+e],processItem:e=>t(e.contents)}),this.vidQueue=M.WorkQueue.mk({queueNames:["vid:"+e],processItem:e=>t(e.contents),concurrent:!1})}async waitForCompletion(){await Promise.all([this.imgQueue.awaitDrain(),this.vidQueue.awaitDrain()])}clearRecentlyProcessed(){this.imgQueue.recentlyProcessed.clear(),this.vidQueue.recentlyProcessed.clear()}get currentPaths(){return[...this.imgQueue.currentQueueContents(),...this.vidQueue.currentQueueContents()]}get currentBaseFiles(){return this.currentPaths.map((e=>o.BaseFile.for(e)))}hasPath(e){for(const t of this.currentPaths)if(e===t)return!0;return!1}get currentVideoJobCount(){return this.vidQueue.currentWorkCount()}get processedCount(){return this.processedImageCount+this.processedVideoCount}get processedImageCount(){return this.imgQueue.processedCount()}get processedVideoCount(){return this.vidQueue.processedCount()}get avgImageProcessingTime(){return this.imgQueue.processMs.p84}get avgVideoProcessingTime(){return this.vidQueue.processMs.p84}async stats(){return{pendingCount:await this.pendingCount(),processedImageCount:this.processedImageCount,processedVideoCount:this.processedVideoCount,avgImageProcessingTime:this.avgImageProcessingTime,avgVideoProcessingTime:this.avgVideoProcessingTime}}currentCounterState(){return{processedImageCount:this.processedImageCount,processedVideoCount:this.processedVideoCount}}itemQuery(e){return P.QueueItem.query().whereIn("queueId",e)}async queueIds(){return[...this.imgQueue.queueIds(),...this.vidQueue.queueIds()]}async pendingCount(){return P.QueueItem.dbl.pluckFirst(this.itemQuery(await this.queueIds()).count("id"))}async pendingContent(e=10){const t=await this.queueIds();return P.QueueItem.dbl.pluckAll(this.itemQuery(t).select("contents").limit(e))}pendingImagesCount(){return this.imgQueue.pendingWorkCount()}pendingVideoCount(){return this.vidQueue.pendingWorkCount()}async etaMs(){return(0,h.sum)([this.imgQueue.etaMs(),this.vidQueue.etaMs()])}recentFileProgress(){return(0,g.compact)([this.imgQueue.recentlyProcessed.last()?.contents,this.vidQueue.recentlyProcessed.last()?.contents])}async enqueueWork(e){if((0,g.isEmpty)(e))return;const[t,i]=(0,s.partition)(e.filter(m.isAssetFileExt),m.isVideoExt);this.logger.info("enqueueWork()",{input:e.map(w.toS),videos:t.map(w.toS),images:i.map(w.toS)}),this.imgQueue.enqueueWork(i.map((e=>({contents:(0,l.toNativePath_)(e)})))),this.vidQueue.enqueueWork(t.map((e=>({contents:(0,l.toNativePath_)(e)}))))}async enqueueOrTouchAssetFiles(e){const t=[],i=f.Settings.copyAssetsToLibrary.valueOrDefault&&!await(0,c.l)(),s=[];await(0,r.withBoundedConcurrency)({name:"enqueueOrTouchAssetFiles",laters:e.map((e=>async()=>{const r=await e.posixFile_(),n={path:r?.nativePath??e.uri,url:(0,p.mkAssetUrl)(e.assetId)?.toString()};if(!0===await e.isFileDeleted()){e.delete();const t={assetId:e.assetId,forceRebuildPreviews:(0,v.isTrue)(e.shown)};(0,a.submitTask_)("repairAsset",t),(0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",details:"file no longer exists",state:u.SyncFileStates.deleted})}if(null==r)return void this.logger.warn("Failed to decode URI to existing file",{af:e});const o=await e.whyNotMatchesFile(),l=i&&(0,v.isTrue)(e.shown)&&!e.uri.startsWith(S.PS_LIBRARY_SCHEME);(0,y.notBlank)(o)||l?((0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",state:u.SyncFileStates.enqueued,details:(0,g.compactBlanks)([o,l?"PS_COPY_ASSETS_TO_LIBRARY is true and this primary variant isn't in the library":""]).join("; ")}),s.push(r)):((0,u.syncReport)().onProgress({...n,from:"enqueueOrTouch()",details:"Library db is already in sync for this file",state:u.SyncFileStates.noop}),t.push(e.id))}))}),b.AssetFile.touch(t),await this.enqueueWork(s),this.logger.info("enqueueOrTouchAssetFiles()",{freshAssetFileIds:t,staleFiles:s})}async enqueueSimpleFiles(e){if((0,g.isNotEmpty)(e)){for(const t of e)(0,u.syncReport)().onProgress({path:(0,l.toNativePath_)(t),from:"AssetFileQueue",state:u.SyncFileStates.enqueued});await this.enqueueWork(e)}}}t.AssetFileQueue=T},58297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetPostUpsertQueue=t.AssetPostUpsertQueueName=void 0;const s=i(79378),r=i(4866),n=i(7162),a=i(47874),o=i(75556),l=i(9497),u=i(30690),c=i(50100);t.AssetPostUpsertQueueName="AssetPostUpsertTasks";const d=(0,r.lazy)((()=>(0,n.mkLogger)("sync.AssetPostUpsertQueue")));t.mkAssetPostUpsertQueue=function(){return l.WorkQueue.mk({queueNames:[t.AssetPostUpsertQueueName],concurrent:!0,async processItem(e){const t=(0,s.parseJSON)(e.contents),i=(0,o.toGt0)(t?.assetId)??(0,o.toGt0)(e.contents);if(null==i)return void d().error("invalid assetId",{qi:e});const r=u.Asset.ops().findById(i);if(null!=r)return(0,c.assetPostUpsertTasks_)(r,(0,a.forceContextOrSetting)({skipAssetTagging:!1,skipPreviews:!1}));d().error("asset not found",{assetId:i})}})}},43600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUpdateQueue=void 0;const s=i(79378),r=i(43414),n=i(11944),a=i(75556),o=i(9497),l=i(52257);t.mkAssetUpdateQueue=async function(e){if(r.Settings.noAssetUpdates.valueOrDefault)return;const t=(0,n.compactBlanks)(await(0,l.enqueueAssetUpdates)());return(0,n.isEmpty)(t)?void 0:o.WorkQueue.mk({queueNames:t,concurrent:!1,processItem(t){const i=(0,s.parseJSON)(t.contents);return e(i?.assetId??(0,a.toInt)(t.contents))},endWhenDone:!0})}},73571:function(e,t,i){"use strict";var s,r,n=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectorySync=void 0;const a=i(24945),o=i(4866),l=i(7162),u=i(19658),c=i(70283),d=i(91464),h=i(47284),f=i(36079),m=i(91641),p=i(4691),g=i(20681),y=i(97463),v=i(3955),w=i(24948),S=i(59220),b=i(31359),P=i(6667),M=i(43414),_=i(67220),T=i(59387),E=i(11944),D=i(39938),k=i(38625),x=i(88491),C=i(6314),F=i(66776),I=i(75556),A=i(17078),O=i(89452),L=i(65548),R=i(33075),N=i(28688);class B extends h.DoneWrapper{static async for({root:e,rootUri:t,fileProcessor:i}){if(await e.clear().isDirectory())return new B(e,t,await N.AssetFileQueue.for(e,i));(0,l.mkLogger)("sync.DirectorySync").warn("Cannot sync "+e+": it's not a directory (or not readable)",{root:e,rootUri:t})}constructor(e,t,i){super("sync.DirectorySync("+e+")",(()=>this.onEnd()),m.EndableRanks.first),s.add(this),this.root=e,this.rootUri=t,this.afq=i,this.start=Date.now(),this._isScanning=!0,this.eta=new b.ETA,this.recentlyScannedDirs=new a.BoundedList(10),this.scannedDirsCount=0,this.preDone=new C.Latch,this.priorProcessedImageCount=0,this.priorProcessedVideoCount=0,this._progress=(0,o.lazy)((()=>L.Progress.insertNew({uri:this.rootUri,volume:this.root.nativePath}))),this.forceDirectoryScan=(0,o.lazy)((()=>{const e=M.Settings.forceSync.valueOrDefault,t=M.Settings.argvScanPaths.values.some((e=>this.root.eql(e)));return this.logger.tap({msg:"forceDirectoryScan",result:e||t,meta:{forceSync:e,isArgvPath:t}})})),this.initialMeta=(0,o.lazy)((async()=>this.forceDirectoryScan()?void 0:this._progress().getMetaAsRecord())),this.saveSyncProgress=(0,o.lazy)((()=>L.Progress.saveSyncState(this)),u.isTest?100:x.secondMs),this.saveLastScannedDirectory=(0,o.lazy)((async()=>{const e=this._progress();e.setMeta(R.ProgressMetaNames.scannedDirectoryCount,this.scannedDirsCount.toString());const t=this.recentlyScannedDirs.at(-1);null!=t&&e.setMeta(R.ProgressMetaNames.lastScannedDirectory,t)}),u.isTest?100:x.secondMs),this.directoryListener=e=>(0,D.mapNotBlank)(e?.nativePath,(t=>(this.scannedDirsCount++,this.recentlyScannedDirs.push(t),this.logger.debug("directoryListener()",{scannedDirsCount:this.scannedDirsCount,dir:e.nativePath}),this.saveLastScannedDirectory()))),this.earliestStartTime=(0,o.lazy)((async()=>{const e=(await L.Progress.times()).find((e=>e.uri===this.rootUri));return e?.lastStartedAt??Date.now()})),this.retryEnqueued=(0,o.lazy)((async()=>{const e=await(0,w.recentSyncReports)();if((0,E.isEmpty)(e))return void this.logger.warn("retryEnqueued(): no-op: no recent sync reports");const t=await(0,S.unprocessedPaths_)({syncReportJsons:e,acceptPath:e=>(0,v.containedByNativePath)({ancestor:this.root,descendant:e})});this.logger.info("retryEnqueued(): parsed prior sync reports to find stuck paths.",{stuck_length:t.length,stuck:t}),await this.afq.enqueueWork(t)})),this.run=(0,o.lazy)((async()=>{const e=await this.initialMeta();if(this.logger.info("setup()",{meta:e}),(0,F.map)(e?.lastScannedDirectory,(e=>this.recentlyScannedDirs.push(e))),(0,c.mapGt0)(e?.processedImageCount,(e=>this.priorProcessedImageCount=e)),(0,c.mapGt0)(e?.processedVideoCount,(e=>this.priorProcessedVideoCount=e)),await n(this,s,"m",r).call(this),this.logger.info("setup() setting isScanning to false."),this._isScanning=!1,await this.afq.waitForCompletion(),M.Settings.retryEnqueued.valueOrDefault&&(this.afq.clearRecentlyProcessed(),await this.retryEnqueued(),await this.afq.waitForCompletion()),await this.maybeEnqueueStaleAssetFiles(),await this.afq.waitForCompletion(),!this.ended){this.logger.info("DONE! Marking Progress as complete and updating meta."),await this.preDone.resolve();const e=await this.progress.refresh();e.setMeta("completedDirectorySync","true"),e.upsert({completedAt:Date.now()}),await this.end()}})),this.progress=(0,g.lazyAsync)({desc:this.name+".progress",timeoutMs:x.secondMs,ttlMs:250,later:async()=>{const e=this.isDone()||this.preDone.isResolved(),t=(0,_.isPaused)()||(0,p.ending)(),i=e?"done":t?"paused":"processing",s=[];e||t||((0,D.mapNotBlank)(this.afq.recentFileProgress(),(e=>s.push(e))),this.isScanning&&s.push("Scanning "+(0,D.firstNotBlank)(this.recentlyScannedDirs.shiftOrFirst(),this.root.nativePath)));const r=[];let n="Processed "+(0,A.plur)(this.processedImageCount,"photo")+" and "+(0,A.plur)(this.processedVideoCount,"video")+".";this.processedImageCount+this.processedVideoCount>0&&r.push(n);const a=await this.pendingCount();!e&&a>0&&(r.push(this.isScanning?"At least":"",(0,A.fmt)(a),"remain to be processed"),n+=` ${this.isScanning?"At least":""} ${(0,A.fmt)(a)} to do.`),a<10&&s.push((await this.afq.pendingContent()).join(", ")),s.push((0,E.compactBlanks)(r).join(" ")),a<10&&s.push();const o=[];o.push((0,d.capitalize)(i)),e||(0,F.map)(this.eta.fmtEstimate(),(e=>o.push(e)));const l=this._progress();this.processedImageCount>1&&l.setMeta(R.ProgressMetaNames.processedImageCount,String(this.processedImageCount)),this.processedVideoCount>1&&l.setMeta(R.ProgressMetaNames.processedVideoCount,String(this.processedVideoCount));const u=await this.percents(),c={state:i,hed:o.join(", "),dek:s,updatedAt:Date.now(),...u};return"done"===i&&(c.completedAt=Date.now()),this.logger.tap({msg:".progress()",level:"info",result:l.assignFromPojo(c)})}}),this.doneLatch.observe(this.run())}async onEnd(){await(0,f.end)(this.directoryWalker),await this.saveSyncProgress.refresh(),await(w.syncReport.prior()?.close())}async maybeEnqueueStaleAssetFiles(){if(!M.Settings.forceSync.valueOrDefault&&(0,k.isTrue)((await this.initialMeta())?.enqueuedStaleFiles))this.logger.info("maybeEnqueueStaleAssetFiles() no-op: prior enqueuedStaleFiles.");else{const e=this._progress(),t=await this.earliestStartTime();this.logger.info("maybeEnqueueStaleAssetFiles() starting enqueue",{assetFileQueuePendingCount:await this.afq.pendingCount()}),await O.AssetFile.ops().batched({onResults:async e=>this.afq.enqueueOrTouchAssetFiles(e),qb:e=>e.whereLike("uri",this.rootUri+"%").andWhere("updatedAt","<",t)}),this.logger.info("maybeEnqueueStaleAssetFiles() finished enqueue",{assetFileQueuePendingCount:await this.afq.pendingCount()}),e.setMeta(R.ProgressMetaNames.enqueuedStaleFiles,"true")}}get processedImageCount(){return this.priorProcessedImageCount+this.afq.processedImageCount}get processedVideoCount(){return this.priorProcessedVideoCount+this.afq.processedVideoCount}processedCount(){return this.processedImageCount+this.processedVideoCount}pendingCount(){return this.afq.pendingCount()}get isScanning(){return this._isScanning}async estimatedScannedPct(){if(!this.isScanning)return 100;const e=100/-(this.scannedDirsCount/500+1)+100;return(0,I.sigFigs)(e,4)}async percents(){if(this.isDone())return{completePct:100,incompletePct:0,scanningPct:0};const e=(0,I.round)(await this.estimatedScannedPct()),t=100-e,i=this.processedCount(),s=await this.pendingCount(),r=0===s&&0===i?0:(0,I.round)(e*(i/(s+i))),n=100-(r+t),a={completePct:r,incompletePct:n,scanningPct:t};if(this.logger.debug("percents(): ",{scannedPct:e,processed:i,pending:s,p:a}),100!==(0,P.sum)([a.completePct,a.incompletePct,a.scanningPct])&&this.logger.warn("percents(): BUGGED",{p:a,processed:i,pending:s,scannedPct:e,scanningPct:t,incompletePct:n,completePct:r}),100===e&&i>7){const e=this.afq,t=(0,T.maxConcurrentImports)(),i=e.pendingImagesCount(),s=e.pendingVideoCount(),r=0===i?void 0:(0,F.map)(e.avgImageProcessingTime,(e=>(0,I.sigFigs)(i*e/t,2))),n=0===s?void 0:(0,F.map)(e.avgVideoProcessingTime,(e=>(0,I.sigFigs)(s*e,2))),a=(0,P.sum)([r,n]);a>0&&(this.logger.info("ETA",{eta:a,imgMs:r,vidMs:n,imgCount:i,imgConcurrency:t,vidCount:s}),this.eta.push(a))}return a}}t.DirectorySync=B,s=new WeakSet,r=async function(){const e=this.forceDirectoryScan(),t=await this.initialMeta();if(!e&&(0,k.isTrue)(t?.completedDirectoryScan))return this.logger.tap({msg:"#maybeRunDirectorySync_(): no-op",result:void 0,meta:{forceDirectoryScan:e,initialMeta:t}});const i=this._progress();this.scannedDirsCount=(0,I.toInt)(t?.scannedDirectoryCount)??0,this.directoryWalker=new y.DirectoryWalker(await this.root.directoryEntry(),this.afq.fileListener,this.directoryListener,t?.lastScannedDirectory),await this.directoryWalker.awaitEnd(),this.logger.info("maybeRunDirectorySync_() completed directoryWalker",{scannedDirsCount:this.scannedDirsCount}),i.setMeta(R.ProgressMetaNames.completedDirectoryScan,"true")}},27864:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryTaggerOperation=void 0;const s=i(4866),r=i(91641),n=i(95557),a=i(4691),o=i(46852),l=i(31359),u=i(6667),c=i(11944),d=i(39938),h=i(6314),f=i(89253),m=i(75556),p=i(17078),g=i(42313),y=i(11254),v=i(96672),w=i(30690),S=i(89452),b=i(36310),P=i(65548);class M extends n.EndableWrapper{constructor(e){super("TagAssetsWithFiles",(()=>null),r.EndableRanks.first),this.priorProgress=e,this.start=Date.now(),this._eta=new l.ETA,this._done=new h.Latch,this._progress=(0,s.lazy)((()=>(0,o.thenOrElse)(this.priorProgress,(()=>P.Progress.insertNew({uri:g.RebuildingURI,volume:"๐Ÿ”„"}))))),this._done.observeQuietly(b.Operation.applyOnce({name:"applyNewTagger",value:y.TagRoots.fs,version:1},(()=>this._run())))}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){if(this.isDone())return(await this._progress()).assignFromPojo({state:"done",hed:"Finished rebuilding your library ๐ŸŽ‰",dek:[],completePct:100,incompletePct:0,scanningPct:0});if(null==this.eta()||null==this.doneCount||null==this.todoCount)return;const e=await this._progress(),t=this.doneCount/(this.todoCount+this.doneCount),i=(0,m.clamp)(0,100,Math.round(100*t)),s=this._eta.fmtEstimate(),r=`Adding ${y.TagRoots.fs} tags to your library`+(0,d.mapNotBlankOr)(s,(e=>", "+e),"โ€ฆ");return e.assignFromPojo({state:"processing",hed:r,dek:[`Tagged ${(0,p.fmt)(this.doneCount)} URIs, ${(0,p.fmt)(this.todoCount)} remain.`],completePct:i,incompletePct:100-i,scanningPct:0})}eta(){if(null==this.todoCount||null==this.doneCount||0===this.todoCount)return;const e=(Date.now()-this.start)/this.doneCount*this.todoCount;return this._eta.push(e),this._eta.avg()}async _run(){return this.todoCount=S.AssetFile.dbl.pluckFirstf((e=>_(e.countDistinct("AssetFile.id")))),this.doneCount=0,S.AssetFile.dbl.batched({onResults:e=>{for(const t of(0,f.groupBy)(e,(e=>e.assetId)).values()){if((0,a.ending)())return;const e=t[0].assetId,i=w.Asset.ops().findById(e);null==i?this.logger.warn("Asset not found",{assetId:e}):((0,v.addFileUriTagsToAsset)(i,t.map((e=>e.uri))),this.doneCount+=t.length,this.todoCount-=t.length)}},qb:(e,t)=>(e=_(e.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",uri:"AssetFile.uri"})),(0,c.isNotEmpty)(t)&&(e=e.andWhere("AssetFile.id",">",(0,u.max)(t.map((e=>e.assetFileId))))),e)})}}function _(e){return w.Asset.shownUnhidden(e.from("AssetFile").join("Asset","Asset.id","AssetFile.assetId"))}t.DirectoryTaggerOperation=M},34875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileSync=void 0;const s=i(34996),r=i(46852),n=i(4866),a=i(65548);t.FileSync=class{constructor(e,t){this.root=e,this._ended=!1,this.uri=(0,n.lazy)((()=>(0,r.thenOrElse)(this.root.uri_(),(()=>"file:///"+this.root.posixPath)))),this._progress=(0,n.lazy)((async()=>a.Progress.insertNew({uri:await this.uri(),volume:this.volume}))),this.name="FileSync("+e+")",this.sync=new s.Deferred(this.name).observe(t)}get ended(){return this._ended}end(){this._ended=!0}isDone(){return this.sync.isSettled}donePromise(){return this.sync.promise}get volume(){return this.root.nativePath}async progress(){return(await this._progress()).assignFromPojo({state:this.sync.isPending?"processing":"done"})}}},74015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelDbUpdater=void 0;const s=i(4866),r=i(36079),n=i(91641),a=i(95557),o=i(4691),l=i(17875),u=i(31359),c=i(11944),d=i(39938),h=i(88491),f=i(87748),m=i(6314),p=i(75556),g=i(17078),y=i(42313),v=i(82798),w=i(49374),S=i(30690),b=i(65548),P=i(12474),M=i(58297),_=i(43600),T=i(52257);class E extends a.EndableWrapper{constructor(e){super("ModelDbUpdater",(()=>this.onEnd()),n.EndableRanks.first),this.opts=e,this._done=new m.Latch,this.eta=new u.ETA,this.updatedAssetIds=new Set,this._progress=(0,s.lazy)((()=>b.Progress.insertNew({uri:y.RebuildingURI,volume:"๐Ÿ”„"}))),this.saveSyncProgress=(0,s.lazy)((()=>b.Progress.saveSyncState(this)),h.secondMs),this._outdatedAssetCount=(0,s.lazy)((()=>(0,T.outdatedAssetCount)())),this.run()}async run(){try{if(this.ended||(0,o.ending)())return;if(await w.Library.instanceRequired().ready,this.assetFileUpdateQueue?.ee.on("processed",this.saveSyncProgress),this.logger.info("Starting asset file updates",{afqName:this.assetFileUpdateQueue?.name,afqEnded:this.assetFileUpdateQueue?.ended,afqRunnable:this.assetFileUpdateQueue?.isRunnable(),workStats:this.assetFileUpdateQueue?.p?.stats()}),await(this.assetFileUpdateQueue?.awaitDrain()),this.logger.info("Completed asset file updates",{afqName:this.assetFileUpdateQueue?.name,afqEnded:this.assetFileUpdateQueue?.ended,afqRunnable:this.assetFileUpdateQueue?.isRunnable(),workStats:this.assetFileUpdateQueue?.p?.stats()}),await(this.assetFileUpdateQueue?.end()),this.eta.clear(),await this.saveSyncProgress(),this.ended||(0,o.ending)())return;this.postUpsertQueue=(0,M.mkAssetPostUpsertQueue)(),this.postUpsertQueue?.ee.on("processed",this.saveSyncProgress),this.assetUpdateQueue=await(0,_.mkAssetUpdateQueue)((e=>this.assetUpdater(e))),this.assetUpdateQueue?.ee.on("processed",this.saveSyncProgress),this.logger.info("Starting asset updates",{aqName:this.assetUpdateQueue?.name,aqEnded:this.assetUpdateQueue?.ended,workStats:this.assetFileUpdateQueue?.p?.stats()}),this.logger.info("run(): waiting for asset updates to complete..."),await(this.assetUpdateQueue?.awaitDrain()),await this.saveSyncProgress(),await(this.assetUpdateQueue?.end()),this.logger.info("run(): waiting for asset previews to complete..."),await this.postUpsertQueue.awaitDrain(),await this.postUpsertQueue.end(),await this.saveSyncProgress.refresh(),this.logger.info("run(): finished"),this.ended||(this._done.resolve(),await b.Progress.saveSyncState(this))}catch(e){(0,l.onError)("ModelDbUpdater.run() failed",e),this._done.reject(e)}}outdatedAssetCount(){return this.assetUpdateQueue?.pendingWorkCount()??this._outdatedAssetCount()}async assetUpdater(e){this.updatedAssetIds.add(e);const t=await this.opts.processor({assetId:e,skipPreviews:!0,skipAssetTagging:!0});if(this.logger.info("ModelDbUpdater.assetUpdater("+e+")",{result:t}),(0,P.isUpdateSuccessResult)(t)){this.postUpsertQueue.enqueueWork([{contents:(0,f.stringify)({assetId:e})}]);const i=t?.assetIdsToUpdate;if((0,c.isNotEmpty)(i)){const e=i.filter((e=>!this.updatedAssetIds.has(e)));(0,c.isNotEmpty)(e)&&S.Asset.dbl.runf((t=>t.whereIn("id",e).update({version:0}))),null==this.assetUpdateQueue||this.assetUpdateQueue.ended?this.logger.warn("non-empty assetIdsToUpdate, and AssetQueue is null/ended"):this.assetUpdateQueue.enqueueWork(e.map((e=>({contents:(0,v.toS)(e)}))))}}return t}async onEnd(){await(0,r.endAll)(this.assetFileUpdateQueue,this.postUpsertQueue,this.assetUpdateQueue),this.assetFileUpdateQueue=this.postUpsertQueue=this.assetUpdateQueue=void 0}isNoOp(){return!(0,p.gt0)(this.assetFileUpdateQueue?.processedCount())&&!(0,p.gt0)(this.postUpsertQueue?.processedCount())&&!(0,p.gt0)(this.assetUpdateQueue?.processedCount())}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){if(this.ended||this.isNoOp())return;const e=this._progress();if(this.isDone())return[e.assignFromPojo({state:"done",hed:"Finished rebuilding your library ๐ŸŽ‰",dek:[],completePct:100,incompletePct:0,scanningPct:0})];const t=this.assetFileUpdateQueue;if(null!=t&&!t.isDone()){const i=t.processedCount(),s=t.pendingWorkCount();(0,p.gt0)(t.processRate.msPerEvent)&&this.eta.push((await this.outdatedAssetCount()+s)*t.processRate.msPerEvent);const{completePct:r}=t.percents(),n=this.eta.fmtEstimate(),a="Rebuilding your library"+(0,d.mapNotBlankOr)(n,(e=>", "+e),"โ€ฆ");return[e.assignFromPojo({state:"processing",hed:a,dek:[`Updating file metadata (${(0,g.fmt)(i)} processed, ${(0,g.fmt)(s)} remain)`],completePct:0,incompletePct:r,scanningPct:0})]}if(null!=this.assetUpdateQueue&&null!=this.postUpsertQueue){const t=this.assetUpdateQueue.pendingWorkCount();this.eta.push(t*(this.assetUpdateQueue.processRate.msPerEvent??h.secondMs));const i=t,s=this.assetUpdateQueue.processedCount(),r=s/(i+s),n=(0,p.sigFigs)(100*r,2),a=this.eta.fmtEstimate(),o="Rebuilding your library"+(0,d.mapNotBlankOr)(a,(e=>", "+e),"โ€ฆ");return e.assignFromPojo({state:"processing",hed:o,dek:(0,c.uniq)([`Refreshing assets and previews (${(0,g.fmt)(s)} processed, ${(0,g.fmt)(t)} remain)`]),completePct:n,incompletePct:100-n,scanningPct:0})}}}t.ModelDbUpdater=E},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const s=i(4866),r=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,s.lazy)((()=>(0,r.mkLogger)("sync.PathsToSync")));const w=(0,s.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function S(){const e=[],i=[];for(const s of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.nativePathToUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=S,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await S()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const s=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",s),s}},38791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.precheckFiles=void 0;const s=i(13779),r=i(24948),n=i(43414),a=i(3874),o=i(25116),l=i(35280),u=i(39938),c=i(88491),d=i(89253),h=i(75556),f=i(89452);t.precheckFiles=async function(e,t=!0){const i=new Map,m=(0,d.groupBy)(e,(e=>e.dir));for(const[e,t]of m.entries()){const s=await(0,a.nativePath2uri)(e);for(const e of t)for(const t of(0,o.uriEncodingVariants)(s+"/"+e.base))i.set(t,e)}const p=[],g=[],y=Date.now()-n.Settings.syncChangedIntervalMs.valueOrDefault;for(const e of(0,s.batches)([...i.keys()],256)){const t=f.AssetFile.ops().allf((t=>t.whereIn("uri",e)));for(const e of t){const t=i.get(e.uri);if(null==t)(0,r.syncReport)().onProgress({path:(await e.posixFile_())?.nativePath??e.uri,from:"Precheck",state:r.SyncFileStates.failed,details:"Failed to correlate prior AssetFile with requested DirectoryEntry"});else if((0,h.gte)(e.updatedAt,y))(0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.noop,details:"synced "+(0,c.fmtHMS)(Date.now()-e.updatedAt)+" ago",url:(0,l.mkAssetUrl)(e.assetId)?.toString()}),p.push({path:t.nativePath,assetId:e.assetId,assetFileId:e.id});else{const i=await e.whyNotNoop();(0,u.blank)(i)?((0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.noop,details:"in sync",url:(0,l.mkAssetUrl)(e.assetId)?.toString()}),g.push(e.id),p.push({path:t.nativePath,assetId:e.assetId,assetFileId:e.id})):(0,r.syncReport)().onProgress({path:t.nativePath,from:"Precheck",state:r.SyncFileStates.enqueued,details:"update needed: "+i,url:(0,l.mkAssetUrl)(e.assetId)?.toString()})}}}t&&f.AssetFile.touch(g);const v=new Set(p.map((e=>e.path)));return{fresh:p,stale:e.filter((e=>!v.has(e.nativePath)))}}},65018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressUpdater=void 0;const s=i(28807),r=i(4691),n=i(56958),a=i(67220),o=i(59694),l=i(24603),u=i(65548),c=i(63216);class d extends s.EndableInterval{constructor(e){super({name:"ProgressUpdater",callback:()=>this.onInterval(),intervalMs:(0,u.ProgressRateMs)()}),this.sync=e,this.prior=[]}async onInterval(){if((0,r.ending)()||(0,a.isPaused)())return void(this.prior=[]);const e=await this.sync();if(null==e)return void(this.prior=[]);const t=await u.Progress.saveSyncState(e),i=(0,o.sortBy)(t,(e=>e.uri)).map((e=>e.toSyncState()));(0,l.eql)(this.prior,i)||((0,n.broadcastEvent_)("updateProgress"),await(0,c.runTagMaintenance)(),this.prior=i)}}t.ProgressUpdater=d},23810:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncCompleted=void 0,t.SyncCompleted={syncCompleted:!0}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const s=i(13779),r=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),S=i(36310),b=i(65548),P=i(71766),M=(0,r.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await b.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),r=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,s.greatestBy)(r,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=r.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=r.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,s.leastBy)(r,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),S.Operation.markOpCompleted({name:S.OperationNames.forceRestartSync}))}function E(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,r.lazy)((async()=>{const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),s=await(0,t.getStaleCompletedAt)(),r=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:r===e.nativePath,status:E(e,s),isNext:e.nativePath===i?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},9515:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncRunner=void 0;const s=i(36079),r=i(91641),n=i(95557),a=i(46852),o=i(79015),l=i(98250),u=i(75123),c=i(6314),d=i(63216),h=i(73571),f=i(85223);class m extends n.EndableWrapper{constructor(e){super("SyncRunner",(()=>this.endCurrentSync()),r.EndableRanks.first),this.fileProcessor=e,this._doneLatch=new c.Latch,this.maybeSetupNextSync()}async progress(){return(0,a.thenMap)(this.currentSync,(e=>e.progress()))}isDone(){return this._doneLatch.isSettled()}donePromise(){return this._doneLatch.promise}endCurrentSync(){const e=this.currentSync;return this.currentSync=void 0,this.currentSyncUri=void 0,(0,s.end)(e)}async setSyncPath(e){if(this.ended)return;await(0,u.clearReaddirCaches)(),(0,o.ee)().emit("clearCache");const t=h.DirectorySync.for({root:l.PosixFile.for(e.nativePath),rootUri:e.uri,fileProcessor:this.fileProcessor});this.syncAndRunNext(e,t)}async syncAndRunNext(e,t){try{const i=this.currentSync=await t;this.currentSyncUri=null==i?void 0:e,null!=i?(this.logger.info("syncAndRunNext(): waiting for completion...",e),await i.donePromise(),this.logger.info("syncAndRunNext(): done",e)):(f.nativePathBlocklist.add(e.nativePath),this.logger.error("syncAndRunNext(): no-op (CHECK ME!)",e))}catch(e){this.logger.error("syncAndRunNext(): caught",{error:e})}return this.maybeSetupNextSync()}async maybeSetupNextSync(){if(this.ended||this._doneLatch.isResolved())return this.logger.info("maybeSetupNextSync(): no-op",{this_ended:this.ended,doneLatch_state:this._doneLatch.state()}),{newPath:null,msg:"ended"};const e=await(0,f.bestPathToSync)();if(null==e)return this._doneLatch.resolve(),this.logger.info("maybeSetupNextSync(): bestPathToSync() returned null, so we're done."),await this.endCurrentSync(),await(0,d.runTagMaintenance)(),{newPath:null,msg:"all paths are synced"};const t=this.currentSyncUri?.nativePath;return null!=t&&t===e.nativePath?{newPath:t,msg:"no-op, current path is already the best"}:(this.logger.info("maybeSetupNextSync(): bestPathToSync() returned a different sync: switching to newBest",{currentSync:this.currentSyncUri,newBest:e}),await this.setSyncPath(e),{newPath:e.nativePath,msg:e.why})}}t.SyncRunner=m},90339:function(e,t,i){"use strict";var s,r,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldGet||function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncService=t.HandledTasks=void 0;const m=i(36079),p=i(28807),g=i(91641),y=i(95557),v=i(4691),w=i(2126),S=i(70259),b=i(37121),P=i(10408),M=i(49379),_=i(90756),T=i(17875),E=i(79141),D=i(79015),k=i(95856),x=i(87489),C=i(79781),F=i(51081),I=i(98250),A=i(24948),O=i(44606),L=i(79403),R=i(62905),N=i(4866),B=i(87308),j=i(69060),z=i(9483),V=i(7162),W=i(19658),U=i(29663),q=i(43414),H=i(14889),G=i(38307),$=i(53719),J=i(76052),K=i(29144),Q=i(11944),Y=i(39938),Z=i(88491),X=i(43947),ee=i(87748),te=i(75556),ie=i(2934),se=i(44726),re=i(82798),ne=i(17146),ae=i(64303),oe=i(49374),le=i(36310),ue=i(13222),ce=i(83148),de=i(20990),he=i(13902),fe=i(87130),me=i(47707),pe=i(93898),ge=i(91877),ye=i(24940),ve=i(63216),we=i(27864),Se=i(74015),be=i(65018),Pe=i(23810),Me=i(9515),_e=i(33206);t.HandledTasks=["runTagMaintenance","checkOperations","repairAsset","repairAssetFile"],t.SyncService=class{constructor(){s.add(this),this.logger=(0,V.mkLogger)("SyncService"),this.progressUpdater=(0,N.lazy)((()=>new be.ProgressUpdater((()=>this.sync())))),r.set(this,0),n.set(this,new S.Promises("SyncService")),a.set(this,(async e=>{this.logger.info("stdinReceiver",{stdin:e});for(const t of(0,Q.compactBlanks)((0,F.splitLines)(e))){const e=(0,ie.parseJSON)(t),i=(0,se.stripPrefixSuffix)((0,re.toS)(e?.path??e?.file??e?.nativePath??e).trim(),{prefix:"'",suffix:"'"});(0,Y.notBlank)(i)&&(0,G.stdoutWrite)(await this.service.promises.enqueue({name:"processFile",l:()=>this.processFile(i)}))}})),this.processFile=async e=>this.currentPaths().includes(e)?this.logger.throw("processFile(): already processing",{nativePath:e}):(this.logger.info("processFile()",{nativePath:e,currentPaths:this.currentPaths()}),h(this,n,"f").push("processFile",(()=>h(this,s,"m",l).call(this,e,q.Settings.maxRetries.valueOrDefault)),e)),this.taskListeners={name:"SyncService",accept:e=>t.HandledTasks.includes(e.name),apply:async e=>{try{return this.logger.tap({msg:"task complete",level:z.LogLevels.warn,result:await h(this,s,"m",u).call(this,e),meta:{task:e}})}catch(t){throw this.logger.warn("task failed",{task:e,error:t}),t}}},c.set(this,(0,N.lazy)((async()=>{(0,D.ee)().on("updateReadyToInstall",(()=>{this.logger.warn("We're about to upgrade: shut down ASAP!"),(0,w.exit)({reason:"Upgrade is ready--exiting now.",status:0})})),await this.service.setup_(),this.logger.info("setup()",{library:q.Settings.libraryDir.valueOrDefault,exitWhenDone:this.exitWhenDone,argvScanPaths:q.Settings.argvScanPaths.value,scanPaths:q.Settings.scanPaths.value,argv:process.argv}),(0,ne.scheduleFileAndProcCleanups)(),await(0,K.setupShimDelegates)(),(0,ue.installBadShaShim)(),await(0,j.m)(),await(0,b.thenOrTimeout)((0,B.r)(),(0,$.commandTimeoutMs)());const e=oe.Library.instanceRequired();await e.ready;const t=await(0,O.getRemoteOrLocalHealthSummary)();(0,R.isHealthCheckLevelFatal)(t.level)&&await(0,w.exit)({reason:"Health check failed: "+t.msg.join(": "),status:1}),await(0,ve.runTagMaintenance)(),(0,ue.listenForInvalidFiles)(),q.Settings.forceRebuildLibrary.valueOrDefault&&(this.logger.info("setup(): forceRebuildLibrary is true: setting all assets to require updates..."),(0,ae.forceRebuildLibrary)()),q.Settings.forceSync.valueOrDefault&&(await(0,me.rmStatDbDirs)(),(0,D.ee)().emit("clearCache"),le.Operation.ensurePendingOp({name:"forceRestartSync",value:""})),q.Settings.dropWorkQueues.valueOrDefault&&(this.logger.warn("Deleting all prior work queues..."),fe.QueueItem.dbl.runf((e=>e.delete())),(0,D.ee)().emit("clearCache")),await(x.SharedState.instance()?.setup()),await(0,b.thenOrTimeout)((0,ce.checkPendingOperations)(),Z.minuteMs),await this.sync(),this.progressUpdater(),this.service.setInputHandler("--force-rebuild-library",(async()=>{this.logger.warn("--force-rebuild-library requested"),await(0,m.end)(this.modelDbUpdater.clear()),await(0,m.end)(this.sync.clear()),(0,ae.forceRebuildLibrary)(),await this.sync(),(0,G.stdoutWrite)({forceRebuildLibrary:"started"})})),this.service.setInputHandler("--check-sync",(async()=>(0,G.stdoutWrite)({checkSync:await this.maybeRestartSyncOnVolumeChange()}))),this.service.setInputHandler("--cleanup",(()=>(0,ne.cleanup_)())),this.service.setInputHandler("--status",(async()=>(0,G.stdoutWrite)({progress:await((await this.sync())?.progress()),currentPaths:this.currentPaths(),whyDoNotRun:(0,J.whyDoNotRun)()}))),this.service.setInputHandler("--clear-cache",(()=>(0,D.ee)().emit("clearCache"))),W.isTest&&U.onProgressEvt.setShim((async e=>console.log((0,ee.stringify)(e)))),(0,D.ee)().on("volumesChanged",(()=>this.maybeRestartSyncOnVolumeChange())),new p.EndableInterval({name:"SyncService.maybeRestartSync()",callback:()=>this.maybeRestartSync(),intervalMs:Z.hourMs,initialDelayMs:Z.hourMs,rank:g.EndableRanks.first}),new p.EndableInterval({name:"SyncService.setVolumesTTL()",callback:()=>(0,he.setVolumesTTL)(),intervalMs:Z.dayMs/4,initialDelayMs:5*Z.minuteMs,rank:g.EndableRanks.first}),new y.EndableWrapper("SyncService end status",(async()=>this.logger.info("end status",await this.status())),g.EndableRanks.first)}))),this.modelDbUpdater=(0,N.lazy)((()=>q.Settings.noModelUpdates.valueOrDefault?void this.logger.info("modelDbUpdater: skipUpdates is set."):h(this,s,"m",d).call(this,"modelDbUpdater",new Se.ModelDbUpdater({processor:ye.handleUpdateCommand}),!0))),this.directoryTaggerOp=(0,N.lazy)((()=>h(this,s,"m",d).call(this,"directoryTaggerOp",new we.DirectoryTaggerOperation))),this.sync=(0,N.lazy)((async()=>{if((0,k.setIsSyncing)(!0),await oe.Library.instanceRequired().ready,q.Settings.argvScanPaths.isEmpty()){const e=this.modelDbUpdater();if(!1===e?.isDone())return e;const t=this.directoryTaggerOp();if(!1===t?.isDone())return t}const e=q.Settings.argvScanPaths.value,t=(0,Q.isNotEmpty)(e)?_e.Syncs.forPaths(e,this.processFile):new Me.SyncRunner(this.processFile);return this.waitForSyncAndCleanup(t),t})),this.exitWhenDone=q.Settings.exitWhenDone.valueOrDefault||q.Settings.argvScanPaths.isNotEmpty(),(0,C.addTaskProcessor)(this.taskListeners),this.service=new de.Service({name:"sync",stdinReceiver:h(this,a,"f")}),h(this,c,"f").call(this).catch((e=>(0,T.onError)(new E.WrappedError("SyncService.setup() failed",{cause:e,fatal:!0}))))}async done(){const e=await this.sync();return null==e||e.isDone()}async status(){const e=await this.sync.prior();return{libraryDir:q.Settings.libraryDir.value,ending:(0,v.ending)(),done:await this.done(),sync:e?.name,progress:await(e?.progress()),summary:L.HealthCheck.summary(),jobs:this.service.promises.stats(),processCount:h(this,r,"f")}}currentPaths(){return h(this,n,"f").pendingWithName("processFile").map((e=>e.payload))}async cancelSync(){const e=await this.sync();null==e||e.isDone()?this.logger.info("cancelSync(): No sync to end."):(this.logger.info("cancelSync(): ending current sync..."),await e.end())}async restartSync(){return await(0,m.end)(this.sync.clear(),Z.minuteMs),this.sync()}async maybeRestartSyncOnVolumeChange(){const e=await this.sync.prior();if(null==e||e instanceof Me.SyncRunner){if(null==e||e.ended||e.isDone())return this.logger.info("maybeRestartSyncOnVolumeChange(): prior sync ended, restarting..."),await this.sync.refresh(),"refresh";{this.logger.info("maybeRestartSyncOnVolumeChange(): calling maybeSetupNextSync()...");const t=await e.maybeSetupNextSync();return(0,ee.stringify)(t)}}return this.logger.info("maybeRestartSyncOnVolumeChange(): no-op, current sync is "+e.name),"noOp:"+e.name}async maybeRestartSync(){const e=this.sync.lastSetAgoMs();if((0,te.lt)(e,H.ShortCommandTimeoutMs))return void this.logger.info("maybeRestartSync(): sync was touched recently.",{lastSetAgoMs:e});const t=await this.sync.prior();t instanceof Me.SyncRunner&&t.ended?(this.logger.info("maybeRestartSync(): SyncRunner ended. Restarting."),this.sync.refresh()):this.logger.info("maybeRestartSync(): We're busy doing something else or the current SyncRunner hasn't ended. no-op.")}async waitForSyncAndCleanup(e){try{await(0,X.delay)(Z.secondMs),await(e?.donePromise()),await(0,X.delay)(Z.secondMs),await this.service.promises.awaitSettled(),await h(this,n,"f").awaitSettled(),await(0,ve.forceRunTagMaintenance)(),W.isTest&&(0,G.stdoutWrite)(Pe.SyncCompleted),(0,k.setIsSyncing)(!1),this.exitWhenDone&&await(0,w.exit)({reason:"Finished",status:0})}catch(e){(0,k.setIsSyncing)(!1),this.exitWhenDone?await(0,w.exit)({reason:"Error: "+e,status:13}):this.logger.error("Sync error",e)}}},r=new WeakMap,n=new WeakMap,a=new WeakMap,c=new WeakMap,s=new WeakSet,o=function(){var e;f(this,r,(e=h(this,r,"f"),++e),"f"),h(this,r,"f")%50==0&&(0,ne.cleanup_)()},l=async function e(t,i){this.logger.info("#processFile()",{nativePath:t,retries:i});try{const r=await(0,pe.importFileToResult)(I.PosixFile.for(t));return W.isTest&&(0,G.stdoutWrite)(r),(0,ge.isErrorResult)(r)?(this.logger.warn("#processFile() error result",{nativePath:t,result:r,retries:i}),!1!==(0,M.isRetriableError)(r.error)&&i>0?h(this,s,"m",e).call(this,t,i-1):r):r}catch(r){this.logger.error("#processFile() caught error",{nativePath:t,retries:i,error:r});const n=(0,E.toWrappedError)(r,{path:t});return!1!==r.retriable&&i>0?(await(0,X.delay)(q.Settings.minDelayBetweenRetriesMs.valueOrDefault),h(this,s,"m",e).call(this,t,i-1)):((0,T.onError)("Failed to process file "+t,{we:n}),{path:t,state:A.SyncFileStates.failed,error:(0,P.errorToS)(n)})}finally{h(this,s,"m",o).call(this)}},u=async function(e){return this.logger.info("enqueueing task",{task:e}),h(this,n,"f").enqueue({name:"#handleTask("+e?.name+")",l:async()=>{switch(await oe.Library.instanceReady(),this.logger.info("handling task",{task:e}),e.name){case"runTagMaintenance":return await(0,ve.runTagMaintenance)(),"success";case"checkOperations":return await(0,ce.checkPendingOperations)(),"success";case"repairAsset":const t=e;return await(0,ye.handleUpdateCommand)({forceSync:!0,skipPreviews:!1,forceRebuildPreviews:!0,...t.args[0]}),"success";case"repairAssetFile":const i=e;return await(0,ye.handleUpdateCommand)({forceSync:!0,...i.args[0]}),"success";default:throw new _.InternalError("unexpected task: "+(0,ee.stringify)(e))}}})},d=function(e,t,i=!1){if(null!=t)return h(this,n,"f").push(e,t.donePromise()).then((()=>{this.logger.info(e+" completed.")}),(t=>(0,T.onError)(e+" failed",t))).finally((async()=>{i&&await h(this,n,"f").push("forceRunTagMaintenance",(0,ve.forceRunTagMaintenance)()),this.sync.refresh()})),t}},33206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Syncs=t.syncForPath=void 0;const s=i(36079),r=i(91641),n=i(95557),a=i(17875),o=i(98250),l=i(24948),u=i(4866),c=i(39938),d=i(6314),h=i(66776),f=i(39784),m=i(73571),p=i(34875),g=i(6492);async function y(e,t){if((0,c.blank)(e))return;const i=o.PosixFile.for(e);if(await i.isDirectory()){const s=await(0,g.posixFileToUriPath)(i);return null==s?((0,l.syncReport)().onProgress({path:e,from:"syncForPath()",state:"failed",details:"Cannot import: URI path could not be built for that path."}),void await(0,l.syncReport)().close()):m.DirectorySync.for({root:i,rootUri:s.uri,fileProcessor:t})}return new p.FileSync(i,t(e))}t.syncForPath=y;class v extends n.EndableWrapper{static forPaths(e,t){return new v("import paths fs sync",(0,f.toA)(e).map((e=>()=>y(e,t))))}constructor(e,t){super(`Syncs(${e})`,(()=>(0,s.end)(this.currentSync)),r.EndableRanks.first),this.laters=t,this._done=new d.Latch,this.run=(0,u.lazy)((async()=>{try{for(const e of this.laters){const t=await e();null!=t&&(this.currentSync=t,await t.donePromise())}this._done.resolve()}catch(e){(0,a.onError)("Syncs.run() failed",e),this._done.reject(e)}})),this.run()}isDone(){return!this._done.isPending()}donePromise(){return this._done.promise}async progress(){return(0,h.map)(this.currentSync,(e=>e.progress()))}}t.Syncs=v},52257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdatesForUri=t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.currentUriRoots=void 0;const s=i(7162),r=i(93813),n=i(6667),a=i(3874),o=i(55713),l=i(46573),u=i(11944),c=i(26588),d=i(82798),h=i(30690),f=i(89452),m=i(36310),p=i(35735);function g(e,t){return e.upsertWorkItems(t.map((e=>({contents:(0,d.toS)(e)}))))}async function y(){return[...await(0,c.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(d.toS)}async function v(e){const t=(0,s.mkLogger)("enqueueAssetFileUpdatesForUri("+e+")"),i=p.Queue.ops().upsertOne({name:(0,p.assetFileUpdatesQueueName2uri)(e)});await m.Operation.applyOnce({name:m.OperationNames.enqueueAssetFileUpdates,version:r.AssetFileVersion,value:e},(()=>{t.info("starting",{queue:i.name}),f.AssetFile.dbl.pluckBatched({onResults:e=>g(i,e),qb:(t,i)=>(t=t.select("id").orderBy("id","asc").where("version","<",r.AssetFileVersion).andWhereLike("uri",e+"%"),(0,u.isNotEmpty)(i)&&(t=t.andWhere("id",">",(0,n.max)(i))),t)})}));const a=i.itemCount();return t.log(0===a?"debug":"info","Added outdated assetFiles:",{queue:i.name,assetFileCount:a}),a?i.name:void 0}async function w(e){const t=(0,s.mkLogger)("enqueueAssetUpdatesForUri("+e+")"),i=p.Queue.ops().upsertOne({name:(0,p.assetUpdatesUri2QueueName)(e)});await m.Operation.applyOnce({name:m.OperationNames.enqueueAssetUpdates,version:r.AssetVersion,value:e},(()=>(t.info("starting",{queue:i}),h.Asset.dbl.pluckBatched({onResults:e=>g(i,e),qb:(t,i)=>(t=t.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","<",r.AssetVersion).andWhereLike("AssetFile.uri",e+"%"),(0,u.isNotEmpty)(i)&&(t=t.andWhere("Asset.id",">",(0,n.max)(i))),t)}))));const a=i.itemCount();if(0!==a)return t.info("Added outdated assets:",{queue:i.name,assetCount:a}),i.name}t.currentUriRoots=y,t.enqueueAssetFileUpdates=async function(){return(0,c.thenCollect)(y(),v)},t.outdatedAssetCount=async function(){const e=await y();return h.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","<",r.AssetVersion).andWhere((t=>e.forEach((e=>t.whereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){return(0,c.thenCollect)(y(),w)},t.enqueueAssetUpdatesForUri=w},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const s=i(3874);async function r(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=r,t.posixFileToUriPath=async function(e){return r(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return r(e,(0,s.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const s=i(7162),r=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,s.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const s=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,r.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=s.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,r.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),s=Date.now()-i;if(sh(e)))}},63216:function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const r=s(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),S=i(46573),b=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),E=i(8199),D=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),A=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return A().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),s=Date.now(),r=A().addContext(".runTagMaintenance()");r.info("starting",{ctx:i});try{r.info("validating all tags..."),C.Tag.validate_(),r.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(r.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),r.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),r.info("vacuuming orphan tags..."),await L()}catch(e){A().warn("runTagMaintenance() failed",e)}const n=Date.now()-s,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),A().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,b.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const s=await(0,t.displayNameForVolsha)(e.name);(0,b.notBlank)(s)?(e.maybeUpsertDisplayName(s),i.info("updated tag",{id:e.id,path:e.path,displayName:s}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,S.volumes)();if(null!=i){const s=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:s}),null!=s?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,b.notBlank)(s.label)?s.label.trim():"/"===s.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,b.notBlankOr)((0,D.stripPrefixSuffix)(s.mountpoint,{prefix:r.default.sep,suffix:r.default.sep}),r.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},22286:e=>{"use strict";e.exports=require("node:https")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=54620);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/web.js b/bin/web.js index f500644..af3ff40 100755 --- a/bin/web.js +++ b/bin/web.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),s=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),s=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:s}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const r=i(6113),s=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:s}=i(35740);s||(s=e=>null!=e&&e instanceof r),e.exports=s},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:s}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),s=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),s=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:s}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),s=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),s=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),s=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),s=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:s}=i(42421),{post:n}=i(97362),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),s=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),s=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),s=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),s=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),s=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),s=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(s.isProd?"":`-${s.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),s=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const s=r(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:s.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class s{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=s},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let s=!(0,r.noColor)();function n(e,t){return i=>s?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){s=e??!(0,r.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),s=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),s=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),s=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),s=i(4866),n=i(98250);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),s=i(40786),n=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),s=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){s(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),s=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),s=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),s=i(74269),n=i(78109);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),s=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),s=i(51498);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),s=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const s=r(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&s.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=s.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},46954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(43383),s=i(49849);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),s=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,s]of(0,u.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,u.keys)(e))if(r[n]=t(n,e[n]),s++,(0,l.gt)(s,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),s=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),s=i(39784),n=i(21142);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const s=i(5712),n=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),E=i(4586),D=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),A=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),O=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))A().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,l.isEmpty)(s))return A().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){A().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){A().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){A().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(A().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,s.pidExists)(r)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),s=t.getTime(),n={...e,cmd:r,startTime:s};return await i.writeJson_(n),A().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void A().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{A().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),s=i(7162),n=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),b=i(46852),S=i(69317),P=i(9288),M=i(51053),_=i(71663),T=(0,n.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],A))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[s.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const A={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},O=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",O.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,A),r=(0,d.onlyReqValued)((0,p.parseFixed)(O,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===s.default.pid))||r.push({pid:s.default.pid,start:new Date(v.StartTs),cmd:"node "+s.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...A,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),s=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),s=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...s)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=s,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return s.promise}(...s)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),s=i(82798);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),s=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,s.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const s=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return s.setShim=e=>{i=e},s.hasShim=()=>null!=i,s}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),s=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,s.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),s=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),s},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),s=this.valueOf(this.store[r]);if(e===s)return{found:!0,index:r};e>s?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),s=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),s=i(18991);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+s+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),s=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),s=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),s=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(92332)),n=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),E=i(46234),D=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new s(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,s=A,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}},r=new WeakMap,s=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=r.isTest?e:e||s}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5685:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(89253),a=i(82798),o=i(59387),l=i(70259);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new l.Promises(e,t)}vacuum(){s(this,r,"f").filterInPlace(((e,t)=>!t.signal.aborted))}enqueue(e,t){for(const t of s(this,r,"f").get(e)??[])t.abort();this.vacuum();const i=new AbortController;return s(this,r,"f").add(e,i),this.p.serial((0,a.toS)(e),(()=>t(i)))}},r=new WeakMap},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,s,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,s,"f")?void 0:Date.now()-d(this,s,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,s,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),s=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let s,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:s):(n=!0,s=(0,r.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>s,o.force=async()=>(await s,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),s=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(s)?(0,d.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=s?b.PermissivePromises:new b.Promises(i,(()=>s))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(s);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){s=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),s=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,s.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),s=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,n.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(s.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...E(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(s);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(s),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return s}t.childEnv=k},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(17718)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),E=i(79141),D=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function A(e,i,r,s=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),s-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),A(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||s?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),A(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95237:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=o(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),b=i(7162),S=i(91464),P=i(36079),M=i(91641),_=i(49379),T=i(98462),E=i(90524),D=i(94845),k=i(51053),x=i(69317),C=i(24905),F=i(52289),I=i(95298),A=(0,c.lazy)((()=>(0,b.mkLogger)("child.ChildService")));async function O(e){const t=(0,S.ensureSuffix)(e,".js"),i=T.BaseFile.projectRoot(),r=T.BaseFile.for(u.default.cwd()),s=(0,D.isPacked)()?[i.join("bin",t),k.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];s.push(r.join("dist","app",t));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,D.isPacked)()?p.KB:128))return A().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:D.isPacked,paths:s.map(v.toS)}});return A().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=O,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class L{static async mk_(e,t={}){const i=t.pathToService??await O(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new L(e,i,t)}constructor(e,t,i){r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,F.serviceExitTimeoutMs)(e),this.logger=(0,b.mkLogger)(this.name);const o=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&o.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,x.spawn)(u.default.execPath,o,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(E.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,S.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=L,r=new WeakSet,s=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),s=i(43414),n=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),E=i(45512),D=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const s=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=s?a.join("$library",i.posixPathFrom(s)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),s=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,s.exit)(0)})),e.parse(s.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),s=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,s.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),s=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(43414),s=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(r.Settings.logColor.envValue=!1),(0,s.map)(e.color,(e=>r.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(43414),s=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),s=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),s=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function I(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function A(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return A(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=A,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),s=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+b:(D=(w+b)/2,D-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*k/(0,s.sqrt)(20+k),F=1+.045*E,I=1+.015*E*x,A=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*A)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),s=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),A=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(A),pixelCount:f.length}),{dominantColors:A,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),s=i(61570),n=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),s=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),s=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),s=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),s=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),s=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),s=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),s=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return s.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function k(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(s=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${E(n)}:${E(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function A(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?s.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(A(e,t),l.dayMs)},t.diffMillis=A,t.closeTo=function(e,t,i){return(0,u.mapOr)(A(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(r+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=s.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},s=(0,M.normalizeZone)(t);if(null!=e&&null!=s&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(s,r):k(e)?.setZone(s,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,T.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),E=i(50140),D=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=A({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function A({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=A;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=A({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),s=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),s=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),s=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),s=i(59694),n=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),s=i(4866),n=i(92507),a=i(43414);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,A=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function O(e){return F(A().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=k(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof s.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=s.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function A(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function O(e,t,i){return(0,u.gt0)(i)&&s.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||A(t,e))&&(!(0,u.gt0)(i)||O(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=A,t.validDay=O,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),s=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),s=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),s=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),s=i(7162),n=i(61253),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),s=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),s=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),s=i(19658),n=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(s.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),s=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,s.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let s;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();s=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:s});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),s=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),s=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),s=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),s=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},34879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(20681),s=i(69317),n=i(22143),a=i(53719),o=i(85890);t.sqliteVersion_=(0,r.lazyAsync)({later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),s=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function x(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),s=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(14889),o=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),s=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),s=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),s=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),s=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),s=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},96416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(4866),s=i(39938),n=i(87748),a=i(17078),o=i(7162),l=i(62936),u=i(10408),c=i(95725),d=i(76531),h=i(82041),f=i(82341),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),s=i(82798),n=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),s=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),s=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!s.isProd&&!(0,n.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),s=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(87561)),n=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(s.default.readFileSync(r)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(n))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),s=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),s=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),s=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),s=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),s=i(88491),n=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),b=i(6231),S=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),s=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,s.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),s=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),s=i(87489);function n(e,...t){return s.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,r.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),s.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),s=i(4866),n=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,s.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let s=!1;t.isSyncing=function(){return s},t.setIsSyncing=function(e){s!==e&&(s=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),s=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,s.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,s.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),E=i(43383),D=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),A=i(75556),O=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),X=i(80294),Z=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),se=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,A.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,A.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),s=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=s,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let s=!1;if((0,P.isEmpty)(i))return;const n=be((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),s||(s=p(this,r,"m",f).call(this,e));s&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,A.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,O.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},s=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?s.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(s.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Z.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,s),this.save(),s)}}t.SharedState=Se,s=Se,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),b.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:s}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(s)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Z.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(s,s,"f",u)),ce.Settings.cacheDir.watchLater(p(s,s,"f",u)),ce.Settings.sharedStateDir.watchLater(p(s,s,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,se.nativePathsEqlSync)(e,s.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(s.instance()),s.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(s,s,"f",l).call(s);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new s(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),s=i(79015);let n=!1;(0,r.later)((()=>(0,s.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},28941:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiHealthRouter=void 0;const s=r(i(66860)),n=i(43383),a=i(79403),o=i(77368);t.ApiHealthRouter=class{constructor(e="/api/health"){this.mountpoint=e,this.router=(0,n.defer)((()=>s.default.Router().get(this.mountpoint,(0,o.wrap)(this.constructor.name+".health",this.health)))),this.health=async(e,t)=>{t.json(await a.HealthCheck.awaitSettled())}}}},77368:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableCache=t.truthyQuery=t.extractLang=t.requestLang=t.extractTagPath=t.jsonOrRedirect=t.getSeedOrRedirect=t.getFit=t.getSeed=t.wrap=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(98510),u=i(33912),c=i(31869),d=i(86768),h=i(82798),f=i(13779),m=i(7162),p=i(70283),g=i(7383),y=i(53525),v=i(79141),w=i(36297),b=i(22189),S=i(50080),P=(0,r.lazy)((()=>(0,m.mkLogger)("express.Handlers")));function M(e){return(0,l.opt)(e).filter(n.notBlank).map(h.toS).map((e=>e.split(","))).map(s.compactBlanks).map((e=>e.map((e=>e.split(";").map((e=>e.trim())))))).flatMap((e=>(0,f.greatestBy)(e,(([,e])=>(0,p.firstGt0)((0,p.extractFloat)(e),1))))).map((([e])=>e)).get()}t.wrap=function(e,t){return async(i,r,s)=>(0,g.time)(e,(()=>(0,S.wrapWithToast)({f:()=>t(i,r,s),response:r})))},t.getSeed=function(e){return(0,u.toSeed)(e.query.seed)},t.getFit=function(e){return c.ThumbFits.validOrElse((0,h.toS)(e.query.fit),c.ThumbFits.square)},t.getSeedOrRedirect=function(e,t){const i=(0,u.toSeed)(e.query.seed);if(null==i){let i=(0,b.requestedUri)(e);"/tag/"===i.path&&(i=i.with({path:"/tag"})),i.query.append("seed",(0,h.toS)((0,u.prngSeed)())),t.redirect(i.toString())}return i},t.jsonOrRedirect=function(e,t){if(null==e)return(0,S.sendErrorToast)(new v.WrappedError("Internal error: jsonOrRedirect(null)"+y.InternalErrorFlag,{fatal:!1,doNotSend:!0}),t,404);for(const i of[d.XLocationRedirect,d.XLocationReplace]){const r=e[i];(0,n.notBlank)(r)&&(P().debug("jsonOrRedirect(): "+i,r),t.setHeader(i,r),t.status(w.HttpStatus.SeeOther))}return t.json(e)},t.extractTagPath=function(e){const t=e.replace(/^(?:\/api)?\/tag\/?/,""),i=t.split("/").map(decodeURIComponent),r=(0,n.blank)(t)?[]:i;return P().info("extractTagPath()",{path:e,result:r,trimmed:t,tagPath:i}),r},t.requestLang=function(e){const t=e.headers["accept-language"];return M(Array.isArray(t)?t.join(","):t)},t.extractLang=M,t.truthyQuery=function(e,t){return(0,o.mapOr)(e.query[t],(e=>!(0,a.isFalse)(e)),(()=>!1))},t.disableCache=function(e){e.setHeader("Cache-Control","no-store, max-age=0"),e.setHeader("Pragma","no-cache"),e.setHeader("Expires","Fri, 01 Jan 1990 00:00:00 GMT")}},47058:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onFinished=void 0,t.onFinished=function(e,t){let i=!1;e.on("error",(r=>{i||(i=!0,t(r,e))}));const r=()=>{i||(i=!0,t(null,e))};for(const t of["end","finish","close"])e.on(t,r);return e}},53235:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectRouter=void 0;const s=r(i(66860)),n=i(83769),a=i(36297),o=i(50080);t.redirectRouter=function(e){return s.default.Router().use(((t,i)=>(0,n.isAjaxRequest)(t.headers)?(0,o.sendRedirectionToast)({response:i,redirectOrReplace:"redirect",url:"/splash"}):i.redirect(a.HttpStatus.Found,e)))}},68079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.referrer=t.isXhr=void 0;const r=i(82798),s=/^XMLHttpRequest$/i;t.isXhr=function(e){return e.xhr||null!=s.exec((0,r.toS)(e.header("X-Requested-With")))},t.referrer=function(e){return e.header("Referer")}},77659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequestLogger=void 0;const r=i(66860),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(7162),u=i(17875),c=i(79403),d=i(7258),h=i(81026),f=i(60346),m=i(43414),p=i(36297),g=i(47058),y=i(22189);t.RequestLogger=class{constructor(){this.logger=(0,l.mkLogger)("web.RequestLogger"),this.responseTimes=new f.Average,this.accessLogger=m.Settings.logWebRequests.valueOrDefault?new h.LogWriter((0,n.firstNotBlank)(m.Settings.logWebDir.valueOrDefault,m.Settings.logDir.valueOrDefault),{processName:(0,s.lazy)((()=>"webrequest"))}):void 0,this.router=(0,r.Router)().use(((e,t,i)=>{const r=Date.now(),s=e.method,n=`${e.protocol?.toUpperCase()}/${e.httpVersion}`,l=`${s} ${(0,y.requestedUri)(e)} ${n}`,h="/updates"===e.path||"/api/splash"===e.path||"/api/status"===e.path?void 0:setTimeout((()=>this.logger.warn("Request is still processing: "+l,{elapsedMs:Date.now()-r})),4*(this.responseTimes.p84??a.secondMs));(0,g.onFinished)(t,(i=>{(0,o.map)(h,clearTimeout),null!=i&&(0,u.onError)(l,{error:i});const a=p.HttpStatusIs.success(t.statusCode)||p.HttpStatusIs.redirect(t.statusCode),f=Date.now()-r,m={from_ip:e.ip,protocol:n,method:s,statusCode:t.statusCode,ok:a,elapsedMs:f,runState:c.HealthCheck.runState(),userAgent:e.headers["user-agent"]};null!=i&&(m.error=i),this.responseTimes.push(f),(0,d.logBroadcaster)()?.log(a?"info":"warn","HttpRequestLogger",l,m),this.accessLogger?.log("info","",l,m),null==d.logBroadcaster.prior()&&null==this.accessLogger&&this.logger.log(null==i&&a?"debug":"warn",l,m)})),i()}))}}},22189:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addXSettingsHandler=t.requestedUri=void 0;const r=i(4866),s=i(43947),n=i(87748),a=i(42041),o=i(68074),l=i(79015),u=i(69060),c=i(43414),d=i(19209),h=i(67220),f=(0,r.lazy)((()=>({protocol:"http",host:c.Settings.hostname.valueOrDefault??"localhost",url:"/"})));t.requestedUri=function(e,t){const i={...f(),...t};return d.URI.parse((e?.protocol??i.protocol)+"://"+(e?.headers?.host??i.host)+(e?.originalUrl??i.url))};const m=(0,r.lazy)((()=>"lite"));async function p(){m.set(await(0,u.t)()),y.unset()}const g=(0,r.lazy)((()=>(0,c.isProd)()?"":"+"+(0,o.nowLocal)())),y=(0,r.lazy)((()=>{const e={ver:a.version+g(),paused:(0,h.isPaused)(),ll_vh:c.Settings.lazyLoadExtraVh.valueOrDefault,tier:m()};return Buffer.from((0,n.stringify)(e)).toString("base64")}));(0,s.later)((()=>{(0,l.ee)().on("settingsChanged",(()=>y.unset())),(0,l.ee)().on("reloadLicenses",p),u.m.watch(p),(0,l.ee)().on("pause",(()=>y.unset())),(0,l.ee)().on("resume",(()=>y.unset()))})),t.addXSettingsHandler=function(e,t,i){t.setHeader("X-Settings",y()),i()}},9786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serveStaticGz=void 0;const r=i(39938),s=i(82798),n=i(7162),a=i(48783),o=i(91464),l=i(53525),u=i(98462),c=i(63526),d=i(77368),h=/\.asar\/?/i;t.serveStaticGz=async function(e){const t=(0,n.mkLogger)("serveStaticGz"),i=u.BaseFile.for(e),f=await i.descendants((e=>e.ext.endsWith(".gz"))),m=(0,a.toMap)(f,(e=>(0,r.mapNotBlank)((0,c.extMimetype)((0,o.stripSuffix)(e.ext,".gz")),(t=>["/"+(0,o.stripSuffix)(e.posixPathFrom(i),".gz"),{contentType:t,nativePath:e.nativePath}]))));return t.debug("ready to serve",[...m.keys()]),0===m.size&&t.error("Can't read "+i+". Please visit https://forum.photostructure.com/ for help."+l.FatalErrorFlag),(0,d.wrap)("serveStaticGz",(async(e,i,r)=>{if(null!=e.path.match(h))return i.sendStatus(404);const n=m.get((0,s.toS)(e.path));return null==n?r():(t.debug("get",{path:e.path,result:n}),i.set("Content-Encoding","gzip"),i.set("Content-Type",n.contentType),i.sendFile(n.nativePath))}))}},41749:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSentEventsRouter=void 0;const s=r(i(66860)),n=i(11944),a=i(39938),o=i(91641),l=i(95557),u=i(83837),c=i(232),d=i(77368);class h extends l.EndableWrapper{constructor(e){super("SSERouter("+e+")",(()=>this.close()),o.EndableRanks.first),this.path=e,this.streams=[]}router(){return s.default.Router().get(this.path,(0,d.wrap)(this.name,this.updates.bind(this)))}close(){this.streams.map(u.endStream),this.streams.length=0}async updates(e,t){if(this.ended)return void t.sendStatus(503);this.logger.info("Sending updates to "+(e.ip??e.ips));const i=(0,u.remoteDesc)(e.socket);t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),this.streams.push(t),t.once("error",(e=>{(0,n.removeSame)(this.streams,t),this.logger.warn("onError("+i+")",{error:e})})),t.once("close",(()=>{(0,n.removeSame)(this.streams,t),this.logger.debug("stream to "+i+" closed. ("+this.streams.length+" remain)")}));const r=(0,n.compact)(this.firstEvents(e,t));(0,n.isNotEmpty)(r)&&(this.logger.info("firstEvents",{firstEvents:r}),t.write((0,c.mkEventStream)(...r)))}endStream(e){(0,u.endStream)(e),(0,n.removeSame)(this.streams,e)}writeToStreams(...e){const t=(0,c.mkEventStream)(...e);if(this.logger.info("writeToStreams",{events:e,payload:t}),!(0,a.blank)(t))for(const e of this.streams)if(!0===e?.closed||null==e?.socket)this.endStream(e);else try{e.write(t)}catch(t){null==e.socket||e.closed?this.endStream(e):this.logger.warn("writeToStreams failed to write to stream",{stream:(0,u.remoteDesc)(e.socket),error:t})}}}t.ServerSentEventsRouter=h},50080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapWithToast=t.expressErrorHandlerWithToast=t.sendErrorToast=t.send404Toast=t.sendWarningServerToast=t.sendRedirectionToast=t.sendServerToast=t.requireEnabled=t.requirePlus=void 0;const r=i(4866),s=i(66776),n=i(86768),a=i(23418),o=i(48652),l=i(50530),u=i(7162),c=i(10408),d=i(49379),h=i(69060),f=i(83769),m=i(36297),p=i(22189),g=(0,r.lazy)((()=>(0,u.mkLogger)("express.ServerToastHelpers")));function y({response:e,toast:t,httpStatusCode:i,reload:r}){return(0,s.map)(i,(t=>e.status(t))),g().warn("sendServerToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,httpStatusCode:i}),e.json({toast:t,reload:r})}function v(e,t,i){g().warn("sendErrorToast",e);const r=(0,d.stripErrorFlags)((0,c.errorToS)(e));y({response:t,toast:{text:404===i?"Not found":"Well, darn, that didn't work",uuid:r,details:r,type:(0,d.isFatalError)(e)?"error":"warning",button1Text:"Return home",button1Url:"/"+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor},httpStatusCode:i??m.HttpStatus.ServiceUnavailable})}t.requirePlus=async function(e,t,i){if(await(0,h.l)()){const e={toastPlusOnly:!0};return t.status(m.HttpStatus.Forbidden),t.json(e)}return i()},t.requireEnabled=function(e){return(t,i,r)=>e.valueOrDefault?r():y({response:i,toast:{text:"This has been disabled by your administrator.",details:`(see setting "${e.name}")`,type:"warning"},httpStatusCode:m.HttpStatus.Forbidden})},t.sendServerToast=y,t.sendRedirectionToast=function({response:e,toast:t,url:i,redirectOrReplace:r}){if((0,f.isAjaxRequest)(e.req.headers)){const s="replace"===r?n.XLocationReplace:n.XLocationRedirect;return e.setHeader(s,i),g().warn("sendRedirectionToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,key:s,url:i}),e.json({toast:t})}return e.redirect(i)},t.sendWarningServerToast=function({response:e,toast:t,httpStatusCode:i,reload:r}){return t.type??(t.type="warning"),y({response:e,toast:t,httpStatusCode:i,reload:r})},t.send404Toast=function({text:e,details:t,response:i,httpStatusCode:r=404}){return y({response:i,toast:{text:e,details:t,type:"warning",button1Text:"Go home",button1Url:(0,o.mkHomeFullPath)()+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor,timeout:!1},httpStatusCode:r})},t.sendErrorToast=v,t.expressErrorHandlerWithToast=function(e,t,i,r){null==e?r():v(e,i)},t.wrapWithToast=async function({f:e,response:t}){try{await e()}catch(e){(0,s.map)((0,l.toErr)(e),(e=>v(e,t)))}}},1597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.viewRouter=void 0;const s=r(i(66860)),n=i(77368);t.viewRouter=function({path:e,view:t,modeler:i}){return s.default.Router().get(e,(0,n.wrap)(t+"Router",(async(e,r)=>{const s=await(i?.(e,r))??{};return s.nonce=r.locals?.cspNonce,r.render(t,s)})))}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(87561)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),s=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),E=i(88491),D=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),A=i(98510),O=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),X=i(2073),Z=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),se=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const s=(0,he.resolve)(i),n=new Se(s,t);return be().set(i,n),be().set(s,n),n}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Z.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*E.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),s=i(17310),n=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),s=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),s=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),s=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,s.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const s=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(s);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(s,(async(e,i)=>{g().trace("callback",{nativePath:s,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:s}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(s,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,s.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),E=i(20902),D=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),A=i(98462),O=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:A.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:se,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),b=i(77696),S=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,s.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,r,"m",a).call(this)}),o(this,s,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,s=new WeakMap,r=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,b.fmtFullDuration)(this.staleMs," ")});const i=await l(this,r,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,S.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,s,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),s=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,s.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),s=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,s.pick)(await(0,r.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),s=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(66776),s=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),_=i(92332),T=i(11944),E=i(37609),D=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),A=i(20636),O=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,s,Math.max(Date.now(),w(this,s,"f",n)+1),"f",n),(0,T.compactBlanks)([q.TokenRadix.encode(w(this,s,"f",n)),N.serviceName.prior(),(0,O.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,O.toS)(e))?.groups?.pid)}static for(e){return w(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=s,s,(i=w(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(s,s,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(s,s,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,A.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),s=i(44726),n=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),E=i(79015),D=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),A=i(95725),O=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,A.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,s,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,s,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,s,"f")});const e=c(this,s,"f"),i=await(0,O.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,s,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,s,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,A.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,s,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,s,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),s=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44470)),n=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(6005)),n=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),s=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),s=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),s=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),s=i(44726),n=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),s=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const r=await Promise.race([T(e,t),D(e,t)]);return t.halt(),r}(t.nativePath)))}async function T(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function E(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(g.isLinux?r===s:(0,m.equalsIgnoreCase)(r,s))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=E,t.grandParentBasename=function(e){return E(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=x(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),F([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("โ€ฆ"),F([...s,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await s.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),E=i(61570),D=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),A=i(14889),O=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),X=i(25116),Z=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),se=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:A.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,O.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,O.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,O.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:A.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(A.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(A.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function A(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function O(e){return[...A(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=A,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...A(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...A(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...A(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>s.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(s.default.join((0,t.execDir)(),"resources"),s.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=s.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),s=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),s=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),s=i(51081);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=E(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(s===h.Timeout&&(0,p.onTimeout)({soft:!1}),s!==h.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):E(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const s=r(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return s.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),s=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},57294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.showFileInFolder=void 0;const r=i(5712),s=i(17718),n=i(4866),a=i(11944),o=i(7162),l=i(51053),u=i(71663),c=i(43414),d=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ShowFileInFolder")));async function h(e,t){try{(0,s.spawn)(e,t,{detached:!0,stdio:"ignore"}).unref()}catch(i){d().warn("spawn() failed",{err:i,cmd:e,args:t})}}t.showFileInFolder=async function(e){if(await e.isEmpty())return!1;if(c.Settings.showFileInFolderUsesThunar.valueOrDefault&&l.isLinux)return async function(e){return h("dbus-send",["--type=method_call","--dest=org.xfce.Thunar","/org/xfce/FileManager org.xfce.FileManager.DisplayFolderAndSelect",`string:"${e.dir}"`,`string:"${e.base}"`,'string:""','string:""'])}(e);if((0,a.isNotEmpty)(c.Settings.showFileInFolderCommand.values)){const t=c.Settings.showFileInFolderUsesFileUri.valueOrDefault?e.fileuri():e.nativePath,i=[...c.Settings.showFileInFolderCommand.values,t],r=i.shift();return d().info("custom showFileInFolderCommand: running",{cmd:r,args:i}),h(r,i)}return l.isLinux?async function(e){return h("nautilus",["-s",e.fileuri()])}(e):l.isWin?async function(e){const t=e.nativePath.replace(/"/g,"").replace(/'/g,"''");try{return await u.PowerShell.instance().execute(`start explorer.exe -ArgumentList '/select,"${t}"'`,r.SimpleParser),!0}catch(t){return d().warn("explorerSelect("+e+") failed",t),!1}}(e):!!l.isMac&&async function(e){return h("open",["-R",e.nativePath])}(e)}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),s=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const s=r(i(87561)),n=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(P(r),P(s));if(null==n||n>1)return"unmatched "+i+": "+r+" โ‰  "+s}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const s=r(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),s=i(6314);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),E=i(91641),D=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),A=i(18849),O=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,s,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,O.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,s,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,A.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),s={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([s],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return l(this,n,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,s,"f")}}t.SyncReport=$,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,s,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,s,"f").nativePath),this.logger.info("Opening new report: "+l(this,s,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,s,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,s,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),s=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),s=i(14889),n=i(95725);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),s=i(34996);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},81286:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(10408),a=i(96593),o=i(83135),l=i(79403);t.exiftoolHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifToolโ€ฆ",settings:[],later:async()=>{try{const e=await(0,a.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,o.ver)(e),(0,r.tt)((0,a.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}catch(e){return{level:"error",msg:"Something's amiss with ExifTool: "+(0,n.errorToS)(e)}}}})))},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(93977),o=n(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},2882:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(43383),s=i(15203),n=i(13699),a=i(79403);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directoriesโ€ฆ",settings:[],later:n.externalDirectoryCheck})))},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),s=i(79403),n=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),E=i(66776),D=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),A=i(13779),O=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),X=i(18295),Z=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,s,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,s,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,s,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,s,"f",l).toA()}static addLoadingMsg(e){v(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Z().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,s,"f",h).entriesByCountDesc()}),(0,E.map)((0,A.leastBy)(e,(e=>[v(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,s,"f",h).incr(e.msg))),Z().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return v(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=s.summary();if(t.settledCountv(s,s,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>s.onResultChange(),onError:()=>s.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,A.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,s=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,s,"f",n),(e=>!e.isPending)),v(this,s,"f",n)},m=function(e){const t=Z().tap({level:"info",msg:"#summary()",result:(0,X.summarizeHealthChecksSync)({errors:v(this,s,"f",l),skipPending:v(this,s,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,s,!0,"f",u),t.state!==v(this,s,"f",c).last?.state&&v(this,s,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Z().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=s.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new O.BoundedList(10)},u={value:!1},c={value:new O.BoundedList(10)},d={value:new O.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(s,s,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(s,s,"m",m).call(s))),Q.resetDebounced=(0,N.debounce)((()=>s.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),s=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},46747:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(4866),s=i(36535),n=i(43383),a=i(77125),o=i(7162),l=i(19658),u=i(29405),c=i(79015),d=i(82041),h=i(81286),f=i(2882),m=i(79403),p=i(61099),g=i(71664),y=i(28482),v=i(22627),w=i(32940),b=i(17938),S=i(40715),P=i(11560),M=i(44454),_=i(93763),T=i(97596),E=i(74113),D=i(23119),k=i(59415),x=i(20610),C=i(9335),F=i(12358),I=i(84729),A=i(42386),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test checkโ€ฆ",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,k.settingsSystemHealthCheck)(),(0,D.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,M.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,_.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,I.videoHealthCheck)(),(0,A.volumeHealthCheck)(),(0,F.versionHealthCheck)(),l.isProd||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},61099:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(71923),u=i(15203),c=i(83135),d=i(79403);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC toolingโ€ฆ",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},71664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(66776),a=i(10408),o=i(22143),l=i(15299),u=i(49849),c=i(83135),d=i(79403);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"โ€ฆ",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK","jpegtran is a supported version.",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),s=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},28482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(24586),l=i(82341),u=i(10408),c=i(3955),d=i(15203),h=i(51053),f=i(43414),m=i(82041),p=i(32421),g=i(79403),y=i(91499);async function v(){const e=await(0,l.setupLibraryDirs_)();return(0,m.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}async function w(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(f.Settings.libraryDir.toEnvLine(f.Settings.libraryDir.defaultValue))}`]};const t=await(0,p.mountpoints_)(),i=(0,c.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[y.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`];return null!=t&&(0,a.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}return await v()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}.`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}}async function b(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:"No PhotoStructure library is open"};if(!(0,m.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",f.Settings.libraryDir.hasValue()?(0,r.tt)(f.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await v():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}t.libraryDirectoriesCheck=(0,n.defer)((()=>g.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directoriesโ€ฆ",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,d.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:(0,d.isDocker)()?w:b})))},22627:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(75556),l=i(61570),u=i(17078),c=i(82341),d=i(42648),h=i(43414),f=i(46573),m=i(79403);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)โ€ฆ",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},17938:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(97742)),n=i(36535),a=i(43383),o=i(46954),l=i(83135),u=i(79403);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.jsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},40715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(43383),s=i(27175),n=i(51053),a=i(79403);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directoryโ€ฆ",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},11560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(43383),s=i(55463),n=i(79403);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating systemโ€ฆ",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},44454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(10408),a=i(51053),o=i(71663),l=i(83135),u=i(79403);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShellโ€ฆ",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},93763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(34879),a=i(10408),o=i(83135),l=i(79403);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLiteโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},97596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(75556),o=i(24586),l=i(42648),u=i(29405),c=i(60052),d=i(51053),h=i(79403);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission levelโ€ฆ",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},74113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(17078),a=i(43414),o=i(77016),l=i(79403);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},23119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(43383),s=i(82041),n=i(79403),a=i(59415);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settingsโ€ฆ",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},59415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(17078),o=i(91464),l=i(10408),u=i(98250),c=i(82041),d=i(98024),h=i(79403);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},20610:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=t.sharpHealthCheck=void 0;const s=r(i(39084)),n=i(71017),a=r(i(57441)),o=i(43383),l=i(24603),u=i(87748),c=i(61570),d=i(10408),h=i(27175),f=i(79403);async function m(e){const t=e??(0,n.join)(h.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(t,{failOn:"error"}),r=await i.resize(31,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,l.eql)((0,c.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:31,height:32,channels:3}),"Unexpected sharp output: "+(0,u.stringify)(r.info))}t.sharpHealthCheck=(0,o.defer)((()=>f.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharpโ€ฆ",settings:[],later:async()=>{try{return await m(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,d.errorToS)(e)]}}}}))),t.testSharp_=m},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),s=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},9335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(43414),l=i(11053),u=i(79403);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system loadโ€ฆ",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},12358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(57310),a=i(79403);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure versionโ€ฆ",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},84729:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(46517),u=i(15203),c=i(83135),d=i(79403);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video toolingโ€ฆ",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},42386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(20636),l=i(17078),u=i(13779),c=i(14889),d=i(51053),h=i(7903),f=i(69551),m=i(53719),p=i(46573),g=i(79403);t.volumeHealthCheck=(0,a.defer)((()=>g.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumesโ€ฆ",settings:[],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:d.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,p.volumes)(),(0,m.commandTimeoutMs)());if(i===o.Timeout){const i=await(0,o.thenOrTimeout)(d.isWin?(0,f.getLocalVolumesWin_)():(0,h.dfPosixRawLocal_)(),c.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===o.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following mountpoints:",(0,s.li)(a.map((e=>e.mountpoint)))]};const[g,y]=(0,u.partition)(i,(e=>!0===e.remote));return{level:"ok",msg:["Volumes seem OK",(0,l.plur)(y.length,"local volume")+" and "+(0,l.plur)(g.length,"remote volume")+" checked."]}}})))},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),E=i(43414),D=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),A=i(14489),O=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,s.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const s=i.sha??await r.sha();if(null!=s)if(!0!==await(0,t.isBadSha)(s))try{return await this._build(r,i)}catch(t){e.push(t),L().set(s,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,O.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:a,height:o,sha:l,mimetype:u}=t;if(null==s||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(r,s);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),s=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),s=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),s=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),s=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),s=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),E=i(68107),D=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function A(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:A}),t._imageHash_=A,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),b=i(60346),S=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),E=i(72461),D=i(36143),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function I({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function A(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=I({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=I({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),A=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(v)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=A,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:A,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=I,t.isSimilarImage=A,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return A(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},34956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matchAndWriteRotation_=t.matchRotation=void 0;const r=i(4866),s=i(61570),n=i(33714),a=i(7162),o=i(7383),l=i(96593),u=i(31195),c=i(84685),d=i(72461),h=i(32148),f=(0,r.lazy)((()=>(0,a.mkLogger)("img.MatchRotation")));async function m(e,t){return(0,o.time)("img.matchRotation",(async()=>{const i=await(0,d.imageHash)(e),r=await(0,d.imageHash)(t),s=(0,h.compareImageHashes)(i,r);if(null!=i&&null!=r&&null!=s)return f().tap({level:"info",msg:"matchRotation()",result:{rotation:s.bRotation,exemplarImageHash:i,destImageHash:r,imageHashComparison:s},meta:{src:e,dest:t}});f().warn("failed to compute image hashes",{a:e,b:t})}))}t.matchRotation=m,t.matchAndWriteRotation_=async function(e,t,i=0){const r=await m(e,t);if(null==r)return;const a=(0,n.normalizeRotation)(r.destImageHash.rotation+r.rotation+i);if(f().info("matchRotation() computed newRotation",{currentRotation:r.destImageHash.rotation,additionalRotation:i,rotationToMatch:r.rotation,newRotation:a}),null==a)return void f().warn("Can't compute final orientation",{newRotation:a,file:t.nativePath,r});const o=(0,c.rotationToWriteTag)(a);if((0,s.isEmptyObj)(o))return void f().warn("rotationToWriteTag() returned null",{newRotation:a,mimetype:r.destImageHash.mimetype,file:t.nativePath});const d=await(0,u.ensureHistoryRecords)(await t.sidecar(),(0,u.mkHistoryRecords)(u.Actions.set,o));return await(0,l.writeTags_)(t,o),f().tap({level:"info",msg:"matchAndWriteRotation_()",result:{...r,writtenTags:o,rotation:a,historyRecords:d},meta:{exemplar:e,dest:t}})}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},35254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(4866),s=i(18941),n=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),s=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),s=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),s=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(889),n=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),E=i(84685),D=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),A=i(49312),O=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),O=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||O||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:O,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=s.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*s.secondMs},p1:{x:20*o.MB,y:12*s.secondMs}},p={p0:{x:11*o.MB,y:12*s.secondMs},p1:{x:26*o.MB,y:24*s.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,s=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+s+n+c+d),dbMs:i,tagMs:s,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),s=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),s=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),E=i(49586),D=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),A=i(68107),O=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),s=D.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,L.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,O.commandTimeoutMs)()}),s.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const r=j("transcode",e),s=$.get(t.nativePath);if(null!=s&&!(0,n.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:s.name}),s.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),s=(0,x.extractDurationSec)(r),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,s={src:e,...V(e,d)},n=J(o,s.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(s.width=(0,u.roundEven)(e.width),s.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));s.dest=i,s.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(s));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...A(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),s=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,s.lazy)((()=>(0,r.toGt0)(n.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),s=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...E,...D,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),A=[];function O(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});A.push(r)}}I.on("error",O),I.stderr.on("data",O);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,s.isNotEmpty)(A))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:A,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),s=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),s=i(43414),n=i(69060);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),s=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),E=i(43414),D=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function A(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function O(e,i,r,s){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await A(e),sids:null!=s?s:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await O((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=A,t.v=O,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await O(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),r=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return O(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,s.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),s=i(4866),n=i(39938),a=i(10508);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function A(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,A,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},59714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const r=i(43383),s=i(66776),n=i(7162),a=i(29731),o=i(46852),l=i(4586),u=i(82341),c=i(56958),d=i(98462),h=i(33501),f=i(69060),m=(0,r.defer)((()=>(0,n.mkLogger)("writeLicense")));async function p(e,t){return(await(0,o.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,f.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof h.L))}async function g(e,t,i){if(null!=t)if((await p(t,i)).some((t=>t.cmp(e)>=0)))m().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,a.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,c.broadcastEvent_)("reloadLicenses"),m().info("saveIfBetter(): wrote to "+i),i}catch(e){return void m().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,f.vok)(e,"candidate",t);if(null==i)return m().error("!ok",e);await g(i,(0,u.libraryDataDirPosixFile)()?.join((0,f.k)().d),t),await g(i,(0,s.map)((0,l.configDir)(),(e=>d.BaseFile.for(e).join((0,f.k)().d))),t),await f.m.refresh()},t.licensesInDirectory=p,t.saveIfBetter=g},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),s=i(88491),n=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),b=i(92781);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),s=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),s=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),s=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),s=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),s=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(4866),s=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),s=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),s=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>s(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),s=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,s.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),s=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),s=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),E=i(3955),D=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),A=i(98968),O=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,A.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,A.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,A.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,A.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,A.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),s=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),E=i(83837),D=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),A=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,s,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,A.recentLogEntries)()),(0,A.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),s=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),s=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),s=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,s.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const s=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&s.push(y.ConsoleLogger.instance()),(0,n.map)((0,b.logBroadcaster)(),(e=>s.push(e))),l.rootLoggers.set(s),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,s.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const E=(0,s.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,s=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),s=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),s=i(89965);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),s=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),s=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),s=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),s=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),s=i(3331);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),s=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},38786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableServer=void 0;const r=i(36079),s=i(91641),n=i(83837);t.EndableServer=class{constructor(e,t){this.name=e,this.server=t,this._ended=!1,(0,r.addEndable)(s.EndableRanks.service,this)}get ended(){return this._ended}end(){return this._ended=!0,(0,n.closeStream)(this.server)}}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),s=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),s=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),s=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),s=i(4866),n=i(82798);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),s=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),s=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),s=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),s=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),s=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),s=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),s=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),s=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),s=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,s.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,s.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),s=i(39784),n=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),s=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(g.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),s=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),s=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),s=i(63774);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),s=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,s.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,s.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,s.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,s.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),s=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),E=i(7560),D=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),A=i(51053),O=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),X=i(26764),Z=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),se=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:A.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,O.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,O.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Z.ColorDistanceFunctions.ciede2000,strEnum:Z.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:se.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(s.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(s.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),s=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>s.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:s.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),E=i(98462),D=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),A=i(95699),O=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(O.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",H),(0,T.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(s),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"old"}),await s.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function X(e){return Q(z(e))}async function Z(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Z,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),s=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),s=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),s=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),s=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),s=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),s=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},77016:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(61570),s=i(91464),n=i(29405),a=i(60052),o=i(43414);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a)null==a.value.opts.fromEnv(r)&&i.push({envKey:n,msg:`The value "${e[n]}" isn't valid for this ${a.value.constructor.name}.`});else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),s=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),s=i(91464);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),E=i(54809),D=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),A=i(43414),O=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(A.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?A.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:A.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(s))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function q(e,t){if(A.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(A.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(A.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!A.Settings.usePathsToInferDates.valueOrDefault||!A.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:A.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",U(t,A.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??s("tags",U(t,A.Settings.capturedAtTagsFallback.values))??(n?void 0:s("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:s("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",q(e,t)))??(n?void 0:s("path",H(e)))??(A.Settings.useStatToInferDates.valueOrDefault?s("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,A.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),s=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(889),n=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),E=i(21084),D=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),A=i(2023),O=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),X=i(54988),Z=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),se=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,Z.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Z.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Z.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,A.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,A.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Z.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,A.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Z.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),s=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),s=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),s=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function A(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),A(i,s,n)},t.ensureHistoryRecords=A},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,l.toDated)(t[r]);if(null==s||(0,h.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),s=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),s=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),s=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),s=i(75556),n=i(43414);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),s=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(r.length)),l=n(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),s=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),E=i(75123),D=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),A=i(96593),O=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,A.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),s=(0,D.findFileIndex)(e,r);if(s<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,A.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),s=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),s=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(s,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),s=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),s=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),s=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),s=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},33611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(4586),s=i(98250);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),s=i(39036);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),s=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},73037:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(82798),s=i(13779),n=i(49849),a=i(39036);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},17953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(61570),s=i(44726),n=i(39036);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},83135:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(39938);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},57310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.systemUserAgent=t.userAgent=t.checkVersion_=t.currentChannel=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(19067),l=i(9678),u=i(54883),c=i(7162),d=i(55463),h=i(14889),f=i(42041),m=i(20681),p=i(4586),g=i(76531),y=i(69060),v=i(43414),w=i(53719),b=i(15425),S=i(33611),P=i(38846),M=i(73037),_=i(17953),T=i(39036),E=i(83135),D=(0,a.defer)((()=>(0,c.mkLogger)("VersionCheck")));async function k(){return v.Settings.allowUserAgent.valueOrDefault?x():l.SimpleAppName}async function x(){return l.SimpleAppName+"/"+f.version+" ("+(0,d.osFullName)()+") "+(0,u.EditionType)().toLowerCase()+"/"+await(0,y.t)()}t.currentChannel=function(){const e=[v.Settings.updateChannel.valueOrDefault,(0,P.channel)()].map((e=>T.UpdateChannels.ordinal(e))).sort()[0];return T.UpdateChannels.values[e]??v.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(!v.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===v.Settings.optOut.value?e.push("Set "+(0,s.tt)(v.Settings.optOut.toEnvLine(!1))+" to enable."):!1===v.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,p.configDir)();if(null==i||!await(0,g.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const l=e?.installedVersion??f.version,c=(0,T.extractUpdateChannel)(l),d=(0,T.eligibleForChannel)(c),h=a.versions.filter((e=>d.includes(e.channel))).map((e=>e.version)),m=e?.latestVersion??(0,M.semverLatest)(...h);if(null==m)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+v.Settings.updateChannel.toEnvLine()]};const y=(0,T.extractUpdateChannel)(m),w="You are running "+(0,u.EditionName)()+" "+(0,E.ver)(l),b="The latest published "+(0,s.tt)(y)+" build is "+(0,E.ver)(m),S=y===c?void 0:"You should consider switching to the "+(0,s.tt)(y)+" channel.",P=Date.now()-a.updatedAt,_="Last checked "+(P{const e=(0,S.channelVersionsCache)(),i=await(0,b.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",config:{headers:{"User-Agent":await k()},timeout:h.ShortCommandTimeoutMs},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:f.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,_.isUpdateChannelVersion)(e)))||r.updatedByVersion!==f.version){if(i.fromCache)return D().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();D().throw("getChannelVersions_(): Invalid response",{result:r})}return D().tap({msg:"getChannelVersions_()",result:r})}})},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),s=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),s=i(55412),n=i(46573);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),s=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await A()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function A(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(I)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=A},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),E=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,s.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),s=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),s=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),E=i(43414),D=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function O(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){O(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(O),E.Settings.scanPaths.watchLater(O),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),O()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=T){if(g.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),s=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),s=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),E=i(91464),D=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),A=i(20902),O=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),X=i(11142),Z=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),se=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=s.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){se().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:ne}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){se().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));se().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return se().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const s=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return se().debug("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return se().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function ge(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,U.friendlyname)(e);return(0,D.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return se().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return se().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,O.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return se().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(se().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void se().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,O.onError)("Timed out getting local volume metadata")));if(null==e)return void se().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;se().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){se().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,O.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return se().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(se().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},232:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkEventStream=void 0;const r=i(39938),s=i(87748),n=i(37086);t.mkEventStream=function(...e){let t="";for(const i of e)null!=i&&((0,r.blank)(i.event)||(t+="event: "+i.event+"\n"),t+="id: "+(i.id??(0,n.uid)())+"\n",t+="data: "+(0,s.stringify)(i.data)+"\n",t+="\n");return t}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},15425:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const s=r(i(52167)),n=i(43383),a=i(75556),o=i(7162),l=i(14889),u=i(36297),c=(0,n.defer)((()=>(0,o.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,a.gt0)(await t.size())&&(0,a.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await s.default.get(e.url,{timeout:l.ShortCommandTimeoutMs,...e.config}),n=r.data;u.HttpStatusIs.success(r.status)||c().throw("Failed",{url:e.url,response:r});const o=e.preCacheTransform?.(n)??n;return c().info("Fetch success. Caching",{args:e,json:o,cache:t}),await t.writeJson_(o),{data:o,updatedAt:Date.now(),fromCache:!1}}},83769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAjaxRequest=t.isHttpsRequest=t.parseForwarded=void 0;const r=i(39938),s=i(39784),n=i(91464),a=i(43414);function o(e){if((0,r.blank)(e))return{};let t=(0,s.toA)(e).join(";").trim().replace(/^[,;]/,"").replace(/[,;]$/,"");const i={};for(;t.length>0;){const e=t.indexOf("=");if(e<0)break;const r=(0,n.stripQuotes)(t.slice(0,e).trim().toLowerCase());if(t=t.slice(e+1).trim(),/^["']/.test(t)){const e=/['"]\s*(?:[;,]|$)/.exec(t.slice(1))?.index;if(null==e)break;const s=(0,n.stripQuotes)(t.slice(0,e+2).trim());i[r]=s,console.log("quoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+3).trim()}else{const e=/[;,]|$/.exec(t)?.index;if(null==e)break;const s=t.slice(0,e).trim();i[r]=s,console.log("unquoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+2).trim()}}return i}function l(e){return(0,r.blank)(e)||function(e){return Array.isArray(e)&&0===e.length}(e)?void 0:(0,s.toA)(e).join(";")}t.parseForwarded=o,t.isHttpsRequest=function(e){return null!=e&&"false"!==a.Settings.trustProxy.valueOrDefault&&((0,n.equalsIgnoreCase)("https",o(e.forwarded).proto??l(e["x-forwarded-protocol"])??l(e["x-url-scheme"]))||"on"===l(e["front-end-https"])||"on"===l(e["x-forwarded-ssl"]))},t.isAjaxRequest=function(e){return"application/json"===e?.["content-type"]}},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),s=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),s=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),s=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.availableCpus=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),b=i(91641),S=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),E=i(59387),D=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{D().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)},t.availableCpus=function(){if(_.Settings.cpuBusyPercent.valueOrDefault<=0)return;const e=x.instance().idlePct();if(null==e)return;const t=Math.floor((0,T.cpuInfo)().length*(_.Settings.cpuBusyPercent.valueOrDefault/100));return Math.floor(t*(e/100))};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,E.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:b.EndableRanks.first}),r.add(this),s.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??F()}}t.CpuUsage=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,F());const e=new C;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?Math.round(t/r*100):void D().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+S.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let s=!1;function n(){s&&(s=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return s},t.pause=function(e=!0){!1===e?n():s||(s=!0,(0,r.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),s=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),s.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),s=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},84213:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(5712),o=i(79378),l=i(4866),u=i(7162),c=i(79015),d=i(51081),h=i(24409),f=i(11944),m=i(16475),p=i(87748),g=i(75556),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=v,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},29144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=t.workerMethodTimeouts=void 0;const r=i(4866),s=i(92585),n=i(61570),a=i(20636),o=i(12374),l=i(7162),u=i(55568),c=i(4691),d=i(49379),h=i(84571),f=i(43414),m=i(59387),p=i(98023),g=i(84213),y=i(48392),v=i(48011),w=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let b=0;const S=[[v.WorkRequestMethods.buildAssetPreviews_,f.Settings.taskTimeoutMs.valueOrDefault]];async function P(e,...i){let r=(await(0,y.WorkerCluster)()).t;if(r.ended){if((0,c.ending)())return w().warn("onChild(): cluster is ended, running task myself",{method:e,args:i}),v.WorkerFunctions[e](...i);w().warn("onChild(): cluster ended unexpectedly. Restarting.",{method:e,args:i}),r=(await y.WorkerCluster.refresh()).t}const n=(0,t.workerMethodTimeouts)().get(e)??(0,h.statTimeoutMs)(),o={id:b++,method:e,args:i};return(0,s.retryOnReject_)((async()=>{const e=new g.RequestTask(o),t=r.enqueueTask(e);return(0,a.thenOrOnTimeout)(t,n/3,(()=>{w().warn("soft timeout servicing work request",{request:o,timeoutMs:n}),(0,p.onTimeout)()})),(0,a.thenOrTimeoutError)(t,n)}),{maxRetries:f.Settings.maxRetries.valueOrDefault,timeoutMs:n,retryDelay:f.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,d.isRetriableError)(e)})}function M(){for(const e of(0,n.values)(v.WorkerFunctions))e.setShim(void 0)}t.workerMethodTimeouts=(0,r.lazy)((()=>new Map(S))),t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,m.singleThreadMode)()||(0,u.isWorkerService)())w().warn("in single-threaded mode"),M(),await((await y.WorkerCluster.prior())?.end());else for(const[e,t]of(0,n.entries)(v.WorkerFunctions))t.setShim((t=>P(e,t)))},t.clearShims=M},48011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const r=i(75556),s=i(61570),n=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,n.strEnum)(...(0,s.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,r.isNumber)(e.id)}},48392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(5712),s=i(13056),n=i(4866),a=i(7162),o=i(38307),l=i(91641),u=i(69317),c=i(95237),d=i(53525),h=i(51081),f=i(24409),m=i(29663),p=i(59387),g=i(88491),y=i(87748),v=i(75556),w=i(2934),b=i(82798),S=i(24905),P=i(94845),M=i(43414),_=i(75153),T=i(941),E=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.WorkerCluster.prior())?.t.closeChildProcesses()},t.WorkerCluster=(0,n.lazy)((async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return E().throw("Could not find worker.js");E().info("worker.js found at "+e);const t={id:-1,method:"ping",args:[{}]},i=new r.BatchCluster({processFactory:async()=>(E().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,T.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,P.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:S.ChildServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,_.cpuCount)(),e??(0,p.maxCpus)());return E().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}))},941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(10347),s=i(43414),n=i(32421),a=i(38625),o=i(61570);t.workerEnv=async function(){const e={};for(const t of(0,o.values)(s.Settings))t.hasValue()&&!(0,a.isTrue)(t.opts.transient)&&t.addToEnvMaybe(e);return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},45766:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(97742)),n=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),s=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),s=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),s=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),s=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),s=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),s=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),s=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),s=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),s=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},38360:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExampleDomain=void 0;const r=i(11944),s=i(44726),n=["example.com","example.net","example.org","example.edu",".example",".local"].map((e=>(0,s.stripPrefix)(e,".").split(".")));t.isExampleDomain=function(e){const t=e.toLowerCase().split(".");return n.some((e=>(0,r.arrayEndsWith)(t,e)))}},75117:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEmail=t.isEmailMaybe=void 0;const r=i(39938),s=i(38360),n=i(82798);t.isEmailMaybe=function(e){return null!=o(e)};const a=/^(?.+)@(?.[^@\n\r.\u2028\u2029]*\..+)$/;function o(e){const t=a.exec((0,n.toS)(e).trim());if(null==t?.groups)return;const{local:i,domain:o}=t.groups;return(0,r.blank)(i)||(0,r.blank)(o)||(0,s.isExampleDomain)(o)?void 0:{local:i,domain:o}}t.parseEmail=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),s=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,s.isFunction)(e)&&(0,s.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),s=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),s=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),s=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),s=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=s.length;(0,r.filterInPlace)(s,(t=>e(i,t))),t=t||n!==s.length,0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),s=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,s){return!(null==s||!l(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,s.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,b(t)?_(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),s=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),s=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),s=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),s=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),s=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),s=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),s=i(61570),n=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{r&&(0,s.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,s=!0){const n=await o(e,i,s);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const s=i-Date.now();return s<=0?t.Timeout:o(e,s,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return l(e,s,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:s=!0}){const a=await o(e,i,s);return a===t.Timeout?(0,n.tot)(r):a}},31869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ThumbFits=void 0;const r=i(84253);t.ThumbFits=(0,r.strEnum)("aspect","square")},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),s=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),s=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),s=i(82798);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},24760:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeQuote=t.AssetQueryOrderByColumns=void 0;const r=i(84253),s=i(82798);t.AssetQueryOrderByColumns=(0,r.strEnum)("capturedAt","updatedAt"),t.maybeQuote=function(e){return null!=(e=(0,s.toS)(e).trim()).match(/\s/)?`"${e}"`:e}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),s=i(75556);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},42313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(84253);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},86768:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkReplace=t.XLocationReplace=t.mkRedirect=t.XLocationRedirect=void 0,t.XLocationRedirect="X-Location-Redirect",t.mkRedirect=function(e,i){return{[t.XLocationRedirect]:e,toast:i}},t.XLocationReplace="X-Location-Replace",t.mkReplace=function(e,i){return{[t.XLocationReplace]:e,toast:i}}},23418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isServerToast=t.DismissAnchor=t.isToastPlusOnly=void 0;const r=i(39938);t.isToastPlusOnly=function(e){return!0===e?.toastPlusOnly},t.DismissAnchor="#dismiss",t.isServerToast=function(e){return(0,r.notBlank)(e?.text)}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),s=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},73491:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPath=void 0,t.ApiProgressPath="/api/progress"},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),s=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),s=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),s=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const r=i(4866),s=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),b=i(43414),S=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),E=i(94332),D=i(63216),k=(0,r.lazy)((()=>(0,s.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,D.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,r.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:b.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,r.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:b.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,r.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(b.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,r.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),A=(0,r.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),O=(0,r.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(b.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,r.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:b.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,S.compact)([x(),C(),F(),I(),A(),(0,w.LogDirCleanup)(),O(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},64303:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceRebuildLibrary=void 0;const r=i(93813),s=i(30690),n=i(89452),a=i(36310);t.forceRebuildLibrary=function(){s.Asset.dbl.runf((e=>e.update({version:0}))),n.AssetFile.dbl.runf((e=>e.update({version:0}))),a.Operation.dbl.runf((e=>e.where({name:a.OperationNames.enqueueAssetFileUpdates,version:r.AssetFileVersion}).orWhere({name:a.OperationNames.enqueueAssetUpdates,version:r.AssetVersion}).delete()))}},49374:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),E=i(46573),D=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),A=i(61570),O=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,A.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,n=new WeakMap,s={value:void 0}},37831:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveLibrarySettings=t.importSettings=t.librarySettings=void 0;const r=i(7162),s=i(38307),n=i(82341),a=i(10408),o=i(98250),l=i(43414),u=i(82041),c=i(98024),d=i(39938),h=i(24603),f=i(11448),m=i(82798),p=i(9075),g=(0,r.mkLogger)("LibrarySettings");function y(e={}){return g.tap({msg:"librarySettings",level:"info",result:{scanAllDrives:l.Settings.scanAllDrives.valueOrDefault,scanPath:l.Settings.scanPaths.values,copyAssets:l.Settings.copyAssetsToLibrary.valueOrDefault,autoUpdateCheck:l.Settings.autoUpdateCheck.value,allowUserAgent:l.Settings.allowUserAgent.value,reportErrors:l.Settings.reportErrors.value,...e}})}function v(e){l.Settings.scanAllDrives.setValueIfDefined(e.scanAllDrives),l.Settings.scanPaths.setValueIfDefined(e.scanPath),l.Settings.copyAssetsToLibrary.setValueIfDefined(e.copyAssets),l.Settings.autoUpdateCheck.setValueIfDefined(e.autoUpdateCheck),l.Settings.allowUserAgent.setValueIfDefined(e.allowUserAgent),l.Settings.reportErrors.setValueIfDefined(e.reportErrors)}t.librarySettings=y,t.importSettings=v,t.saveLibrarySettings=async function(e,t){const i=o.PosixFile.forMaybe((0,m.toS)(e).trim())?.resolve(),r=y(),w=l.Settings.libraryDir.valueOrDefault,b=i??o.PosixFile.forMaybe(w);let S=Promise.resolve();const P=(0,f.lazy)((()=>{S=S.then((async()=>{try{v(r),l.Settings.libraryDir.value=w,await(0,u.writeSystemSettings_)(),(0,d.blank)(w)||await(0,u.writeLibrarySettings_)(w),await(0,p.restartLibrary_)()}catch(e){g.warn("Failed to roll back to prior settings",{priorSettings:r,priorLibraryDirValue:w,error:e})}}))}));if(null==b)return{error:"Please choose a directory for your library.",ready:S};const M=b?.nativePath!==w;if(M){try{await(0,n.setupLibraryDirs_)(b)}catch(e){return{error:"Failed to set up "+b+". Please choose a different directory for your library. "+(0,a.errorToS)(e)}}g.info("Library directory changed, asking sync to shut down",{prior:w,new:i?.nativePath}),s.StdoutWrite.shutdownSync()}try{v(t);const e=!(0,h.eql)(r,y());if(null==await(0,u.writeLibrarySettings_)(b.nativePath))return P(),{error:"Cannot write to "+b.nativePath+". Please choose a different directory for your library.",ready:S};l.Settings.libraryDir.value=b.nativePath;try{await(0,u.writeSystemSettings_)()}catch(e){return P(),g.warn("Failed to write system settings",e),{error:"Couldn't write your system settings to "+(0,c.systemSettingsFile)()+": "+(0,a.errorToS)(e),ready:S}}return g.info("saveLibrarySettings()",{libraryDirChanged:M,librarySettingsChanged:e,settings:t,priorSettings:r,currentSettings:y()}),(M||e)&&(S=S.then((()=>(0,p.restartLibrary_)({readSettings:!1})))),{msg:"Saved",ready:S}}catch(e){return P(),g.error("Failed to save settings",{error:e}),{error:"Failed to save settings: "+(0,a.errorToS)(e),ready:S}}}},9075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartLibrary_=void 0;const r=i(4866),s=i(7162),n=i(55568),a=i(38307),o=i(79015),l=i(79403),u=i(43414),c=i(82041),d=i(49374),h=(0,r.lazy)((()=>(0,s.mkLogger)("library.RestartLibrary")));t.restartLibrary_=async function(e){(0,n.isWebService)()&&a.StdoutWrite.shutdownSync(),(e?.readSettings??1)&&await c.readSettings.refresh();let t=Promise.resolve();h().warn("Shutting down prior library...");try{t=d.Library.endPriorInstance()}catch(e){h().warn("ending prior library failed:",{error:e})}(0,o.ee)().emit("clearCache"),u.Settings.libraryDir.broadcastChange(),l.HealthCheck.reset();const i=d.Library.instance();return t=t.then((()=>i?.ready)),(0,n.isWebService)()&&(t=t.then((async()=>{const e=await l.HealthCheck.awaitSettled();"ready"===e.state?a.StdoutWrite.restartSync():h().error("Restarted library, but health check summary was not ready",{summary:e})}))),{ready:t}}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),s=i(20902),n=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),b=i(91641),S=i(95557),P=i(4691),M=i(52289),_=i(10408),T=i(27519),E=i(49379),D=i(17875),k=i(79015),x=i(12737),C=i(49857),F=i(7157),I=i(85352),A=i(9483),O=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await Z(e);return await(T.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(X))))}function X(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=X,t.annotateEvent=Z,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[A.LogLevels.fatal,"fatal"],[A.LogLevels.error,"error"],[A.LogLevels.warn,"warning"],[A.LogLevels.info,"info"],[A.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),b=i(7162),S=i(33148),P=i(55568),M=i(25516),_=i(38307),T=i(42041),E=i(95557),D=i(4691),k=i(2126),x=i(7383),C=i(70259),F=i(24905),I=i(44731),A=i(20902),O=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Y=i(39938),X=i(88491),Z=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{x.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,k.exit)({reason:"exit() event",status:0})))}));class se extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,new Q.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,s,(0,b.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,n,"f").promise}get isReady(){return m(this,n,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Y.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Y.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new B.WrappedError(e)}),5*X.secondMs)})),(0,S.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,n,"f").reject():m(this,n,"f").resolve()}catch(e){console.error((0,O.errorToS)(e)),m(this,n,"f").reject((0,te.toErr)(e)),(0,k.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,O.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,Z.later)((()=>(0,k.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,s,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,s,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},59960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdown=void 0;const r=i(4866),s=i(7162),n=i(38307),a=i(4691),o=i(2126),l=i(56958),u=i(11353);let c="unspecified";t.shutdown=function(e){return(0,s.mkLogger)("Shutdown").warn("shutdown()",{reason:e}),c=e,d()};const d=(0,r.lazy)((async()=>{n.StdoutWrite.shutdown(),(0,l.broadcastExit)(),(0,u.setUnrefTimeout)((()=>(0,a.ending)()?void 0:(0,o.exit)({reason:c,status:0})),3e3)}))},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),s=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,s.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),s=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(s.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+s),s):s}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i(0,l.mkLogger)("library.SuggestedLibraryDir")));class I{static async for(e,t){if((0,k.blank)(e))return;const i=await(0,T.bestVolumeForPath)(e,t);if(null==i)return void F().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,m.isLibraryDir)(e);return new I(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=_.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=_.Settings.minDiskFreeGb.valueOrDefault*C.GB){if(this.isLibrary)return;const t=await(0,P.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,b.containsHiddenPathname)(this.nativePath))return F().tap({...i,result:"contains hidden path"});{const e=await(0,w.whyExcludedDirectoryRecursive)(v.BaseFile.for(this.nativePath));if(null!=e)return F().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,y.canRWXFirstExistingAncestor)(this.nativePath)?(0,x.gt0)(e)&&this.availableBytesnew I(e,!1,{mountpoint:"/test",available:C.GB})))});const l=[],d=[],y=await i??await(0,T.volumes)();if(null==y||(0,E.isEmpty)(y))return F().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await I.for(t,y);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(F().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(_.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,p.picturesDir)());const w=[n.default.cwd(),...await(0,S.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,S.childDirectories_)((0,f.homeDir)())),(0,E.filterInPlace)(w,(e=>(0,b.isNotHiddenPosixPath)(e)));for(const e of w)await(0,m.isLibraryDir)(e)&&(F().info("current working dir is a library",e),await v(e));function P(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(F().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,f.homeDir)(),(0,a.AppName)())),await(0,h.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:y,f:e=>async function(e){try{if(await(0,m.isLibraryDir)(e.mountpoint))return F().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,S.childDirectories_)(e.mountpoint)){if(P())break;if(await(0,m.isLibraryDir)(t))F().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,S.childDirectories_)(t)){if(P())break;await(0,m.isLibraryDir)(i)&&(F().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());F().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){F().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),F().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const k=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(k.length>=t)break;k.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(F().debug("adding new path",e),k.push(e))}return(0,E.uniqBy)((0,D.sortBy)(k,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=I,t.suggestedLibraryDirs=(0,o.lazy)((()=>A())),t._suggestedLibraryDirs=A},98505:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(45161),s=i(35796),n=i(54883),a=i(79403),o=i(69060),l=i(95976),u=i(55463),c=i(33407),d=i(55568),h=i(43414),f=i(82041),m=i(45113),p=i(24586),g=i(42041),y=i(11053),v=i(59387),w=i(11944),b=i(39938),S=i(38625),P=i(19067),M=i(66776),_=i(75556),T=i(26588),E=i(44726),D=i(17078),k=i(30690),x=i(89452),C=i(50725);async function F(){if(null==k.Asset.db())return;const e=[];e.push((0,D.plurMetric)(k.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,D.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,D.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const I={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:I[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,M.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,M.map)(y.CpuUsage.instance().busyPct(),(e=>(0,_.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,_.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},51731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(43414),s=i(38625);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,s.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),s=i(85297),n=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),s=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),s=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},18130:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),E=i(88491),D=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class A extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),s=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:s,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,y.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=A,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),E=i(94332),D=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},3382:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelRepair=void 0;const r=i(4866),s=i(7162),n=i(55568),a=i(38307),o=i(10408),l=i(53525),u=i(79403),c=i(43414),d=i(53719),h=i(49374),f=i(9075),m=i(91796),p=i(41593),g=i(94332),y=i(91894),v=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelRepair")));t.dbModelRepair=async function(){return{...await async function(){const e=h.Library.instance();if(null==e)throw new Error("No library set."+l.NoLibraryErrorFlag);const t=await e.dbModelJanitor();if(null==t)throw new Error("No library set (missing dbModelJanitor)."+l.NoLibraryErrorFlag);(0,y.clearDbSetupErrors)();const i=await(0,m.dbModelHealthCheck)().refresh();if(v().info("dbModelRepair: health check result: ",i),c.Settings.dbForceRecover.valueOrDefault)u.HealthCheck.addLoadingMsg("PS_DB_FORCE_REPAIR was set. Trying to repair.");else if("ok"!==i.level)u.HealthCheck.addLoadingMsg(`Database health check failed: ${i.msg}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0;else try{return u.HealthCheck.addLoadingMsg("Running maintenance tasks..."),await(0,p.runMaintenanceTasks)({force:!0}),u.HealthCheck.addLoadingMsg("Backing up the library database..."),await t.forceBackup_(),u.HealthCheck.addLoadingMsg("Validating the library database..."),await t.db.verify_(),u.HealthCheck.addLoadingMsg("No repair needed: maintenance tasks, backup, and integrity tests ran without error."),v().tap({msg:"dbModelRepair()",level:"info",result:{noop:!0,op:"validated"}})}catch(e){u.HealthCheck.addLoadingMsg(`Maintenance, backup, or integrity tasks failed: ${(0,o.errorToS)(e)}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0}(0,n.isWebService)()&&a.StdoutWrite.shutdownSync();const r=await e.dbFsLock();if(!await r.acquire_({timeoutMs:2*(0,d.commandTimeoutMs)(),releaseOnFailure:!1}))return v().throw("Failed to acquire exclusive lock on the library database. Shut down other processes before retrying.");try{await(0,g.assertValidDbInfo_)()}catch(e){u.HealthCheck.addLoadingMsg(`Library database setup was invalid: ${(0,o.errorToS)(e)}. Resetting and restarting.`),await(0,g.libraryDbInfoJsonFile)().unlink(),c.Settings.dbForceRecover.envValue=!0}await(0,f.restartLibrary_)();const s=c.Settings.dbForceRecover.valueOrDefault;return c.Settings.dbForceRecover.unset(),v().tap({msg:"dbModelRepair()",level:"info",result:{op:s?"repaired":"restarted",noop:!1}})}(),state:(await u.HealthCheck.rerunSetup()).state}}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),s=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),s=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,s.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},13915:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeSchemaJsonFile_=t.assertValidDbSchema_=t.schemaJsonFile=void 0;const s=r(i(49411)),n=i(13779),a=i(4866),o=i(7162),l=i(98250),u=i(27175),c=i(11944),d=i(51367),h=i(17078),f=i(91796),m=i(51603),p=(0,a.lazy)((()=>(0,o.mkLogger)("db.DbSchemaValid")));function g(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=g,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,m.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await g(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&p().throw("Db is missing "+(0,h.plur)(t.length,"table")+" : "+(0,d.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)p().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&(p().error("Missing columns",{expected:t,actual:e}),p().throw("Db is missing "+(0,h.plur)(i.length,"column")+" from table "+e.tableName+" : "+(0,d.andList)(i.map((e=>e.name)))))}}p().info("Validated schema.")}catch(e){throw(0,f.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return g(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,m.localTableInfo)(t)},{spaces:2})}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),s=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),E=i(43947),D=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),A=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(I.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,A.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),E=i(85476),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),s=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),E=i(6314),D=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),A=i(9069),O=i(70582),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,O.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,A.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),s=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),s=i(89253);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),s=i(43414),n=i(82798);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},91796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(42648),s=i(10408),n=i(79403),a=i(82041),o=i(36535),l=i(88491),u=i(43383),c=i(49374),d=i(13915),h=i(91894),f=i(77910),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library databaseโ€ฆ",settings:["libraryDir","forceLocalDbReplica"],ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{if(!(0,a.libraryHasSettings)())return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let e,t,i=!1;try{const s=Date.now();if(i=!1,t=c.Library.instanceRequired(),(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(await t.ready,e=await t.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(e),i=!0,await e.verify_(),await e.vacuum(),f.Heartbeat.assertPing_();const n=await t.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(e.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==e?void 0:"Live db is "+(0,o.tt)(e.dbFile.nativePath),null==t?void 0:"Local replica mode is "+(0,o.tt)(await t.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},39946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(4866),s=i(46747),n=i(82041),a=i(91796),o=i(23134),l=i(53829);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},23134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(13779),s=i(7162),n=i(98250),a=i(23872),o=i(79403),l=i(82041),u=i(11944),c=i(36535),d=i(43383),h=i(71766),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directoriesโ€ฆ",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},53829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(7162),s=i(46852),n=i(79403),a=i(43414),o=i(82041),l=i(47044),u=i(53719),c=i(27127),d=i(46573),h=i(11944),f=i(36535),m=i(43383),p=i(51367),g=i(89253),y=i(61570),v=i(71766),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumesโ€ฆ",settings:["scanAllDrives"],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" โ†’ "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},30690:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),E=i(87748),D=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),A=i(89452),O=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=A.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),A.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),A.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,O.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new A.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(A.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof A.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof A.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();A.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=A.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(A.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new A.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,s=W,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),E=i(65642),D=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),A=i(11944),O=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),X=i(13222),Z=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,X.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,A.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,q.assignAllFields)(this,(0,q.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,A.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,A.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=x.URI.parse(this.uri),s=await t.exists();if(null==e||(0,A.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,O.at)((0,O.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,O.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,s=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),s=i(75556);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),s=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},63232:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setAssetRotation_=void 0;const r=i(7162),s=i(5685),n=i(87489),a=i(34956),o=i(11944),l=i(43383),u=i(87748),c=i(75556),d=i(33714),h=i(30690),f=(0,l.defer)((()=>new s.LastOneInWins("Asset")));t.setAssetRotation_=async function(e,t,i){if(!(0,c.gt0)(e))throw new Error("invalid asset "+(0,u.stringify)(e));if(!(0,d.isRotation)(t))throw new Error("setRotation("+t+"): invalid rotation "+(0,u.stringify)(t));return f().enqueue(e,(async s=>async function(e,t,i,s){const c=Date.now(),d=(0,r.mkLogger)("setAssetRotation("+(0,u.stringify)({assetId:e,rotation:t})+")"),f=h.Asset.ops().findById(e);if(null==f)return d.throw("Unknown assetId:"+e);const m=(0,l.defer)((()=>{(0,n.submitTask_)("repairAsset",{assetId:e})}));d.throwIfAborted(s);const p=await i.ap(e).smallestFileForReducer("fit");if(null==p)return m(),d.throw("Missing previews for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const g=f.getAssetFiles();if(null==f.getShown())return m(),d.throw("No primary asset file for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const y=[];for(const e of g)try{const i=await e.posixFile();if(null==i||await i.notExists()){d.info("cannot rotate variation: file is missing",{f:i,af:e});continue}if(null==await(0,a.matchAndWriteRotation_)(p,i,t)){d.info("cannot rotate variation: matchRotation() failed",{f:i,af:e});continue}y.push(await e.upsertIfNeeded_(i.clear(),!0))}catch(t){d.warn("failed to update asset file",{af:e,error:t})}return(0,o.compact)(y),(0,o.isNotEmpty)(y)&&await i.apb(e,g,{forceRebuildPreviews:!0}).build_(),d.info("setRotation("+t+"): completed.",{elapsedMs:Date.now()-c,updatedAssetFiles:y}),y}(e,t,i,s.signal)))}},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),s=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},77910:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(53525),s=i(88491),n=i(75556),a=i(1724);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),s=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),s=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),s=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),E=i(1429),D=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),A=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,A.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),s=[];for(const n of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),s.push(e)}}return s}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),s=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,s.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const s=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=s)return void c().debug("applyOnce(): already done",{priorCompleted:s});const n=this.ops().insertOne(e),o=await t(n);return(0,r.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),D.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:s.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),s=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),s=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),E=i(39784),D=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),A=i(14405),O=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(A.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(A.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(A.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),s=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const s=c.$tableName;this.dbl.runScript([`INSERT INTO ${s}(${s}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),s=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),s=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},78053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeAssetTags_=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(96593),o=i(89452),l=(0,r.lazy)((()=>(0,s.mkLogger)("model.WriteAssetTags")));t.writeAssetTags_=async function(e,t){const i=o.AssetFile.ops().findBy({assetId:e});return(0,n.mapAsync)({name:"writeAssetTags",arr:i,f:e=>async function(e,t){const i=await e.posixFile_();if(null!=i&&!0===await(i?.exists()))return(0,a.writeTags_)(i,t,e.mimetype);l().info("Skipping AssetFile:"+e.id+" (file is missing)",{writeTags:t})}(e,t)})}},77837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(23595),s=(0,i(4866).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},26825:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(44726),o=i(82798);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"ยฌ",and:"โˆง",or:"โˆจ"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},40234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(13779),s=i(11254),n=i(11944),a=i(59694),o=i(39938),l=i(38625),u=i(84253),c=i(82798),d=i(77837),h=i(26825);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[ยฌ(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},4728:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(50764)),n=i(4866),a=i(7162),o=i(19658),l=i(53525),u=i(75556),c=r(i(12436)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!o.isProd&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},66953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(4866),s=i(7162),n=i(85590),a=i(68074),o=i(6667),l=i(43414),u=i(61473),c=i(39938),d=i(38625),h=i(87748),f=i(82798),m=i(18273),p=i(30690),g=i(77837),y=i(26825),v=i(40234),w=i(4728),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",M(t));case v.AssetTermNs.excluded:return T({qb:e,column:"Asset.excludedAt",whereNull:0===M(t)});case v.AssetTermNs.deleted:return T({qb:e,column:"Asset.deletedAt",whereNull:0===M(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+_(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+_(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function M(e){return P(e)?1:0}function _(e){return e.includes("*")?e.split("*").map(_).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function T({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},12436:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(34235)),a=i(11944),o=i(82798);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-ยฌ]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|โˆจ|\|{1,2}) +/,and:/(?:and|AND|And|โˆง|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),s=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,s.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},97840:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function b(){const e=[],i=[];for(const r of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(r)){const s=await(0,v.nativePathToUriPath)(r);null==s?(e.push(r),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",r)):i.push(s)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",r);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await b()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),b=i(36310),S=i(65548),P=i(71766),M=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await S.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),s=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=s.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=s.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,r.leastBy)(s,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),b.Operation.markOpCompleted({name:b.OperationNames.forceRestartSync}))}function E(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,s.lazy)((async()=>{const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),r=await(0,t.getStaleCompletedAt)(),s=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:s===e.nativePath,status:E(e,r),isNext:e.nativePath===i?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const r=i(3874);async function s(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=s,t.posixFileToUriPath=async function(e){return s(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return s(e,(0,r.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),s=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,s.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),E=i(8199),D=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),A=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return A().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=A().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(s.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),s.info("vacuuming orphan tags..."),await L()}catch(e){A().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),A().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},72316:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const r=i(37980),s=i(64063),n=i(9972),a=i(37445),o=i(7127),l=i(51731),u=i(92045),c=i(21625);!async function(){await new r.CLI(o.ServiceNames.web).add(l.ExposeArg,u.LogArgs,n.TimingArg,a.WriteSettingsArg,s.ColorArgs).parse(),new c.WebService}()},36389:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AboutRouter=void 0;const s=r(i(66860)),n=i(14889),a=i(91464),o=i(80294),l=i(77368),u=i(69060),c=i(43414),d=i(47044),h=i(46573),f=i(38625),m=i(88491),p=i(19067),g=i(66776),y=i(75556),v=i(26588),w=i(20636),b=i(17078),S=i(98505),P=i(65548),M=i(85223),_=i(47458);t.AboutRouter=class{router(){return s.default.Router().get("/about",(0,l.wrap)("AboutRouter",this.about.bind(this)))}async about(e,t,i){const r=n.ShortCommandTimeoutMs+m.secondMs,s=await(0,w.thenOrTimeoutAs)({f:(0,S.systemInformation)(),timeoutMs:r,as:[{term:"System information",defn:"Failed to fetch system information: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"}]}),l=await(0,w.thenOrTimeout)((0,v.thenMap)((0,h.volumes)(),(e=>e.map((e=>({ignorable:e.ignorable,mountpoint:e.mountpoint,uuid:e.uuid,volsha:(0,g.map)(e.uuid,d.volsha),size:(0,b.fmtBytes)(e.size,2),free:(0,b.fmtBytes)(e.available,2),full:(0,y.gt0)(c.Settings.minDiskFreeGb.valueOrDefault)&&(0,y.lt)(e.available,c.Settings.minDiskFreeGb.valueOrDefault*b.GB),label:e.label,remote:!0===e.remote?{remote:e.remote,host:e.remoteHost,share:e.remoteShare}:void 0}))).filter((e=>!0!==e.ignorable)))),r);l===w.Timeout&&s.push({term:"volumes() timeout",defn:"Failed to fetch volume metadata: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"});const T=null==P.Progress.db()?void 0:await(0,w.thenOrTimeout)((0,M.syncPathsForUI)(),n.ShortCommandTimeoutMs);T===w.Timeout&&s.push({term:"sync paths timeout",defn:"Failed to fetch sync path metadata: timeout after "+(0,o.fmtMs)(n.ShortCommandTimeoutMs),defnClass:"fail"});const E=await(0,u.b)();return(0,_.render)(e,t,"about",{title:"About PhotoStructure",systemInfo:s,volumes:Array.isArray(l)?l.map((e=>({...e,mountpoint:(0,a.wbrPath)(e.mountpoint)}))):void 0,syncPaths:Array.isArray(T)?T:void 0,subTier:await(0,u.t)(),subTrial:(0,f.isTrue)(E?.l?.trial),subEmail:E?.l?.sub,subExpiresInDuration:(0,g.map)(E?.l?.exp,(e=>(0,p.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,g.map)(E?.l?.exp,m.fmtIsoDate)})}}},86840:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AdminPostRouter=void 0;const s=r(i(66860)),n=i(2126),a=i(79015),o=i(77368),l=i(68079),u=i(50080),c=i(75123),d=i(79403),h=i(82041),f=i(46573),m=i(88491),p=i(43947),g=i(87748),y=i(17146),v=i(9075),w=i(59960),b=i(3382),S=2*m.secondMs;t.AdminPostRouter=class{router(){return s.default.Router().post("/admin/restart",(0,o.wrap)("AdminHealthRouter:restart",this.restart.bind(this))).post("/admin/bounce",(0,o.wrap)("AdminHealthRouter:bounce",this.bounce.bind(this))).post("/admin/refresh/:id",(0,o.wrap)("AdminHealthRouter:refresh",this.refresh.bind(this))).post("/admin/clear-library",(0,o.wrap)("AdminHealthRouter:clear-library",this.clearLibrary.bind(this))).post("/admin/clear-caches",(0,o.wrap)("AdminHealthRouter:clear-caches",this.clearCaches.bind(this))).post("/admin/recheck-tools",(0,o.wrap)("AdminHealthRouter:recheck-tools",this.recheckTools.bind(this))).post("/admin/repair-db",(0,o.wrap)("AdminHealthRouter:repair-db",this.repairDb_.bind(this))).post("/admin/run-maintenance",(0,o.wrap)("AdminHealthRouter:repair-db",this.maintenance_.bind(this))).post("/admin/shutdown",(0,o.wrap)("AdminHealthRouter:shutdown",this.shutdown.bind(this)))}async restart(e,t,i){await(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarted library...",timeout:S},url:"/splash"})}async refresh(e,t,i){const r=e.params.id,s=d.HealthCheck.findById(r);if(null==s)throw new Error("No health check found with id="+(0,g.stringify)(r));const n=await s.refresh();(0,u.sendRedirectionToast)({response:t,toast:{text:"Health check "+r+": "+n.level,timeout:S},url:"/health"})}async bounce(e,t,i){(0,p.delay)(m.secondMs).then((()=>(0,n.exit)({reason:"/bounce requested by "+e.ip,status:0}))),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarting webserver...",timeout:15*m.secondMs},url:"/splash"})}async clearLibrary(e,t,i){await(0,h.clearLibraryDirSetting)(),(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Prior library was unset. Restarting...",timeout:S},url:"/splash"})}async clearCaches(e,t,i){await(0,f.clearVolumesCache)({deleteFileCache:!0}),await(0,c.clearReaddirCaches)(),(0,a.ee)().emit("clearCache"),"/health"===(0,l.referrer)(e)?(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared caches.",timeout:S},url:"/health"}):(0,u.sendServerToast)({response:t,toast:{text:"Cleared caches."},reload:!0})}async recheckTools(e,t,i){(0,a.ee)().emit("clearToolCache"),(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared tool caches.",timeout:S},url:"/health"})}async repairDb_(e,t,i){(0,b.dbModelRepair)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library database repair...",timeout:S},url:"/splash"})}async maintenance_(e,t,i){(0,y.cleanup_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library maintenance jobs...",timeout:S},url:"/"})}async shutdown(e,t,i){(0,p.delay)(S).then((()=>(0,w.shutdown)("requested by "+e.ip))),(0,u.sendServerToast)({response:t,toast:{text:"Shutdown initiated."}})}}},16654:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiAssetRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(70283),o=i(46852),l=i(21142),u=i(80294),c=i(79141),d=i(87489),h=i(77368),f=i(50080),m=i(34928),p=i(69060),g=i(72612),y=i(15203),v=i(43414),w=i(53719),b=i(11944),S=i(59694),P=i(13783),M=i(38625),_=i(88491),T=i(66776),E=i(75556),D=i(61570),k=i(33714),x=i(86768),C=i(11254),F=i(82798),I=i(30690),A=i(10074),O=i(63232),L=i(50725),R=i(78053),N=(0,n.mkLogger)("web.ApiAssetRouter"),B=["hidden","excludedAt","deletedAt"];t.ApiAssetRouter=class{constructor(e){this.previews=e}wrapApi(e,t){return(i,r,s)=>(0,f.wrapWithToast)({response:r,f:async()=>{const s=(0,E.toGt0)(i.params.assetId);if(null==s)return r.sendStatus(400);const n=await(0,o.thenMapOr)(I.Asset.ops().findById(s,{shown:1}),(e=>t(i,s,e)),(()=>this.onMissingAsset(i,s)));if(N.debug(e,{result:n}),null!=n)return(0,h.jsonOrRedirect)(n,r);throw new c.WrappedError("Asset "+s+" wasn't found",{retriable:!1,doNotSend:!0,fatal:!1})}})}router(){return s.default.Router().get("/api/asset/:assetId/info",this.wrapApi("ApiAssetRouter.assetInfo",this.assetInfo.bind(this))).get("/api/asset/:assetId/streams",this.wrapApi("ApiAssetRouter.assetInfo",this.assetStreams.bind(this))).get("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.asset",this.asset.bind(this))).put("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.save",this.save.bind(this))).put("/api/asset/:assetId/resync",this.wrapApi("ApiAssetRouter.resync",this.resync.bind(this)))}async assetInfo(e,t,i){const r=i.getAssetFiles(),s=i.getShown(),n=(0,T.map)(s,(e=>e.getNativePath())),a=(0,g.isLocalhost)(e.ip)&&!(0,y.isDocker)();if(v.Settings.resyncAssetOnVisit.valueOrDefault&&(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!1,forceRebuildPreviews:!1}),null==s||null==n)return void N.error("no shown AssetFile found for "+t,{asset:i,shown:s,shownPathP:n});N.debug("assetInfo()",{assetId:t,shown:s,shownPathP:n,ip:e.ip,showOpenFile:a});const l=i.getTags(),c=await(0,o.mapAsync)({name:"api.assetInfo.tags",arr:l,f:e=>e.toApiTag()}),f=await(0,o.mapAsync)({name:"api.assetInfo.files",arr:r,f:e=>e.toApi(this.previews,s.sha)});return(0,S.sortByInPlace)(f,(e=>[!e.shown,!e.exists,e.nativePath])),{assetId:t,capturedAtLocale:s.capturedAtLocale((0,h.requestLang)(e)),...(0,D.pick)(s,"mimetype","focalLength","iso","aperture","shutterSpeed"),durationHMS:(0,T.map)(s.durationMs,u.durationHMS),fps:s.fps,files:f,tags:c,showOpenFile:a}}async onMissingAsset(e,t,i){const r="next"===e.query.from;N.info("onMissingAsset()",{query:(0,D.entries)(e.query),params:(0,D.entries)(e.params),assetId:t});const s=(0,E.toInt)(String(e.query.priorAssetId)),n=(0,T.mapOr)(i,(e=>e.id),(()=>s));if(null==n)return void N.warn("onMissingAsset(): no context asset available");const l=await(0,o.thenMapOr)(i,(e=>e.capturedAtLocal),(()=>I.Asset.dbl.pluckFirstf((e=>e.select("capturedAtLocal").where({id:n})))));let u=I.Asset.shownUnhidden(I.Asset.query().select("id").limit(1).whereNotIn("id",(0,b.compact)([t,s])));u=r?u.andWhere("capturedAtLocal","<",l).orderBy("capturedAtLocal","desc"):u.andWhere("capturedAtLocal",">",l).orderBy("capturedAtLocal","asc");const c=I.Asset.dbl.pluckFirst(u);return N.warn("Asset redirect",{fromAssetId:n,priorAssetId:s,fromTime:l,toAsset:c}),(0,a.mapGt0)(c,(t=>(0,x.mkReplace)((0,P.assetUrl)({assetId:t,params:[e.query,e.params]}),{text:`Asset ${n} is no longer available.`,type:"info"})))}async asset(e,t,i){const r=i.getShown();if(null==r)return N.error("no shown AssetFile found for "+t+", disabling (for now)."),i.upsert({shown:!1}),N.error("Asset un-shown."),(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i);i.getBeforeAfterId();const s={...i.partialSimpleAsset(),name:r.basename,width:r.width,height:r.height,rotation:r.rotation??0,capturedAtLocale:r.capturedAtLocale((0,h.requestLang)(e)),aspectRatio:(0,m.aspectRatio)(r),durationHMS:(0,T.map)(r.durationMs,u.durationHMS),downloadable:await r.originalDownloadable({brief:!0}),contextTag:await i.whenApiTag(),beforeAssetId:i.beforeId,afterAssetId:i.afterId};if(r.isVideo){const r=await i.videoSources();return await i.getExistingAssetFiles(),(0,b.isEmpty)(r)?(N.warn("no existing files for "+t+", trying to repair, but redirecting user now."),(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i)):{...s,videoAttrs:i.videoAttrs(),videoSources:r}}return{...s,imgAttrs:await i.fitAttrs(this.previews)}}async assetStreams(e,t,i){const r=(0,E.toInt)((0,F.toS)(e.query.limit),{defaultValue:C.BeforeAfterStreamLimit}),s=i.getStreams(r);return N.tap({msg:"assetStreams",result:{assetId:t,assetStreams:await(0,o.mapAsync)({name:"assetStreams",arr:s,f:e=>e.toApi()})}})}async save(e,t,i){if(await(0,p.l)())return N.warn("save(): disabled"),{showTryPlusToast:!0};const r=i.isActive(),s={hidden:(0,M.toBoolean)(e.body.hidden),excludedAt:(0,T.map)((0,M.toBoolean)(e.body.excluded),(e=>e?Date.now():null)),deletedAt:(0,T.map)((0,M.toBoolean)(e.body.deleted),(e=>e?Date.now():null)),rating:(0,T.map)((0,M.toBoolean)(e.body.liked),(e=>e?v.Settings.likeRating.valueOrDefault:null))};if(!(0,b.isEmpty)((0,D.keys)(s))){N.info("save()",{obj:s,body:e.body}),A.AssetRevision.insert(...(0,D.entries)((0,D.omit)(s,...B)).map((([e,r])=>({assetId:t,field:e,priorValue:i?.[e],newValue:r}))));const n=null===s.deleted?null:null!=s.deleted?-1:s.rating;void 0!==n&&await(0,R.writeAssetTags_)(t,{Rating:n}),i.upsert(s),i.isActive()!==r&&L.Tag.deltaAssetCountAndAncestors(i.tagIds(),i.isActive()?1:-1)}const n=i.partialSimpleAsset(),a=(0,k.normalizeRotation)((0,E.toInt)(e.body.rotation));return null!=a&&0!==a&&(await(0,O.setAssetRotation_)(t,a,this.previews),n.rotation=a),n}async resync(e,t){I.Asset.dbl.runf((e=>e.where({id:t}).update({version:0})));const i=()=>I.Asset.dbl.pluckFirstf((e=>e.where({id:t}).select("updateCount"))),r=i();return(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),await(0,l.untilTrue)((async()=>r!==i()),{timeoutMs:(0,w.commandTimeoutMs)(),intervalMs:_.secondMs}),{v:i()}}}},47576:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressRouter=void 0;const l=i(92332),u=i(4866),c=i(14889),d=i(41749),h=i(232),f=i(67220),m=i(11944),p=i(24603),g=i(73491),y=i(65548);class v extends d.ServerSentEventsRouter{constructor(e){super(g.ApiProgressPath),r.add(this),this.updatesProvider=e,s.set(this,void 0),this.updateData=(0,u.lazy)((()=>this.updatesProvider.updates()),(0,y.ProgressRateMs)()),o(this,s,(0,l.setInterval)((()=>a(this,r,"m",n).call(this)),(0,y.ProgressRateMs)()),"f"),this.onEnds.push((()=>clearInterval(a(this,s,"f"))))}firstEvents(){return[]}}t.ProgressRouter=v,s=new WeakMap,r=new WeakSet,n=async function(){if(!(this.ended||(0,m.isEmpty)(this.streams)||(0,f.isPaused)()&&null!=this.updateData.prior()))try{const e=await this.updateData.prior(),t=await this.updateData.refresh();if(null==t)return void this.logger.warn("Failed to fetch updates");if((0,p.eql)(e,t))return void this.updateData.setTTL(Math.min(c.ShortCommandTimeoutMs,this.updateData.ttl()??(0,y.ProgressRateMs)())+500);if(this.ended)return;this.updateData.setTTL((0,y.ProgressRateMs)());const i=(0,h.mkEventStream)({data:t});for(const e of this.streams)e.write(i)}catch(e){this.logger.warn("Failed to send updates",e)}}},6757:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSearchRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(22189),l=i(43414),u=i(46573),c=i(11944),d=i(39938),h=i(38625),f=i(75556),m=i(17078),p=i(24760),g=i(82798),y=i(30690),v=i(14405),w=i(26825),b=i(40234),S=i(4728),P=i(66953),M=(0,n.mkLogger)("web.ApiSearchRouter");t.ApiSearchRouter=class{router(){return s.default.Router().get("/api/search",(0,a.wrap)("ApiSearchRouter.get",this.get.bind(this)))}async get(e,t){const i=(0,g.toStr)(e.query.q," "),r=p.AssetQueryOrderByColumns.validOrElse((0,g.toStr)(e.query.orderby,","),p.AssetQueryOrderByColumns.capturedAt),s=(0,h.isTrue)(e.query.asc),n={column:r===p.AssetQueryOrderByColumns.capturedAt?"Asset.capturedAtLocal":"Asset.updatedAt",order:s?"asc":"desc"},a=(0,f.toGt0)((0,g.toStr)(e.query.offset));if(M.debug("get()",{q:i,orderBy:n,offset:a}),(0,d.blank)(i))return t.json({});const _=(0,b.normalizeQuery)((0,S.parseQuery_)(i));let T=(0,P.defaultAssetQuery)().select({id:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"}).orderBy([n,"Asset.id"]).limit(512);const E=(0,w.findTerm)(_,(e=>"fs"===e.ns))?await(0,u.mountpointToVolsha)():void 0;null!=a&&(T=T.offset(a));const D=null==a?await async function(e,t,i){const r=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().countDistinct("Asset.id"),t))}(t,i),{emptyTrashQuery:s,removeAssetsQuery:n}=function(e){const t=1===(0,w.flatTerms)(e).length,i=t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.deleted)));return{emptyTrashQuery:i,removeAssetsQuery:!i&&t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.excluded)))}}(t);if(0===r)return{description:s?"No assets are marked for trash.":n?"No assets are marked for removal.":"No matching assets."};const a="Found "+(0,m.plur)(r,"asset");if(!s&&!n)return{description:a};const u=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().join("AssetFile","AssetFile.assetId","Asset.id").countDistinct("AssetFile.id"),t))}(t,i),c=a+" ("+(0,m.plur)(u,"file")+")",d={expectedAssetFileCount:String(u)};if(s){const t="Empty trash";return{description:c,buttonText:t,buttonIcon:"trash_forever",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableEmptyTrash.valueOrDefault?{buttonClass:"error",buttonTitle:null,prompt:[`

    Are you sure you want to permanently delete ${(0,m.plur)(u,"file")} comprising ${(0,m.plur)(r,"asset")}?

    `,"","

    To proceed, please enter the number of files that will be deleted:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/empty-trash",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableEmptyTrash" setting.',prompt:null,formAction:null}}}if(n){const t="Remove assets";return{description:c,buttonText:t,buttonIcon:"warning",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableRemoveAssets.valueOrDefault?{buttonClass:"warning",buttonTitle:null,prompt:["

    Are you sure you want to remove "+(0,m.plur)(r,"asset")+" (comprised of "+(0,m.plur)(u,"file")+") from your library?

    ","","

    To proceed, please enter the number of files that will be removed:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/remove-assets",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableRemoveAssets" setting.',prompt:null,formAction:null}}}throw new Error("internal error (mkBanner)")}(e,_,E):void 0;T=(0,P.queryToSql)(_,T,E).distinct();const k=(0,c.compact)(y.Asset.dbl.all(T).map(v.toAssetId)),x={query:{q:i,normalized:(0,w.queryToString)(_,w.NormieQuerySymbols),orderBy:r,asc:s,offset:a??0,nextOffset:k.length<512?void 0:k.length+(a??0)},banner:D,assetIds:k};return M.debug(".get("+(0,w.queryToString)(_)+") result",x),t.json(x)}validatePostRequest(e,t){return M.debug("validatePostRequest",{req_query:e.query,req_body:e.body}),this.validatePost((0,g.toStr)(e.query.expectedAssetFileCount," "),e.body.answer,t)}async validatePost(e,t,i){M.debug("validatePost",{expectedAssetFileCount:e,answer:t});const r=(0,f.toInt)((0,g.toS)(e));if(null==r)return"Cancelled: the expected number of files was missing from the request.";const s=(0,f.toInt)(t);if(null==s)return"Cancelled: missing user input.";const n=await y.Asset.dbl.pluckFirst(i().join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id"));return r!==n?`Cancelled: the number of files has changed from ${(0,m.fmt)(r)} to ${(0,m.fmt)(n)}. Reload this page and try again.`:s!==r?`Cancelled: you entered "${t??""}" and we expected "${r}".`:{assetFileCount:n}}}},40687:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSplashRouter=void 0;const a=i(41749),o=i(79403),l=i(42041),u=i(88491),c=i(61715),d={loading:"โณ Loading...",welcome:"๐Ÿ‘‹ Welcome!",ready:"โœ… Ready",failed:"โš ๏ธ Something's not right. Gathering details..."};class h extends a.ServerSentEventsRouter{constructor(){super("/sse/splash"),r.set(this,null)}runStateEvent(e=o.HealthCheck.runState()){const t=e===c.RunStates.loading;return t&&this.streams.length>0?n(this,r,s(this,r,"f")??setInterval((()=>{this.writeToStreams(this.runStateEvent())}),u.secondMs),"f"):null!=s(this,r,"f")&&(clearInterval(s(this,r,"f")),n(this,r,null,"f")),this.logger.tap({msg:"runStateEvent()",level:"warn",result:t?{event:"msg",data:o.HealthCheck.loadingMsg()??d[e]}:{event:"settled",data:d[e]},meta:{state:e}})}firstEvents(){return[{event:"version",data:l.version},this.runStateEvent()]}}t.ApiSplashRouter=h,r=new WeakMap},34312:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSystemRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(70283),l=i(38307),u=i(56958),c=i(87489),d=i(77368),h=i(50080),f=i(76531),m=i(24948),p=i(43414),g=i(67220),y=i(11944),v=i(39938),w=i(38625),b=i(75117),S=i(87748),P=i(75556),M=i(17078),_=i(82798),T=i(64303),E=i(59960),D=i(30690),k=i(36310),x=(0,n.lazy)((()=>(0,a.mkLogger)("web.ApiSystemRouter")));async function C(e,t){var i,r;return x().tap({msg:`countAssetFiles(${t})`,result:(i=e.locals)[r="countAssetFiles-"+t]??(i[r]=await D.Asset.dbl.pluckFirst(D.Asset.shownRemovable(t).join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id")))})}function F(e){return async(t,i,r)=>{const s=(0,_.toStr)(t.query.expectedAssetFileCount," "),n=(0,o.extractInt)(t.body.answer);x().debug("validatePostCounts",{expectedAssetFileCount:s,answer:n});const a=(0,P.toInt)((0,_.toS)(s));if(null==a)return(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:"The expected number of files was missing from the request"}});const l=(0,P.toInt)(n);if(null==l)return(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:"User answer was missing"}});const u=await C(i,e);return a!==u?(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:`The number of files has changed from ${(0,M.fmt)(a)} to ${(0,M.fmt)(u)}. Reload this page and try again.`}}):l!==a?(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:`You entered "${n??""}" and we expected "${a}".`}}):r()}}function I(e){if("deletedAt"===e)return k.OperationNames.applyDeleted;if("excludedAt"===e)return k.OperationNames.applyExcluded;throw new Error("invalid RemovableColumn "+e)}async function A(e,t){const i=await async function(e,t){var i,r;return(i=e.locals)[r="countAssets-"+t]??(i[r]=await D.Asset.dbl.pluckFirst(D.Asset.shownRemovable(t).countDistinct("Asset.id")))}(e,t),r=await C(e,t);x().warn("setting "+t+" to unshown...",{assetCount:i,assetFileCount:r});const s=k.Operation.ops().insertOne({name:I(t),value:(0,S.stringify)({assetCount:i,assetFileCount:r})});x().warn("inserted",{ops:s});const n={shown:0,updatedAt:s.createdAt};n[t]=s.createdAt;const a=D.Asset.dbl.run(D.Asset.shownRemovable(t).update(n));x().warn("updated assets",{result:a,obj:n}),await(0,c.submitTask_)("checkOperations")}async function O(e,t){return await A(t,"deletedAt"),(0,h.sendServerToast)({response:t,reload:!0,toast:{text:"Emptied trash",details:"Files will be deleted soon.",type:"success"}})}async function L(e,t){return await A(t,"excludedAt"),(0,h.sendServerToast)({response:t,reload:!0,toast:{text:"Assets have been removed from your library.",type:"success"}})}t.ApiSystemRouter=class{constructor(e){this.openFileService=e,this.getState=(e,t)=>{const i={paused:(0,g.isPaused)()};return t.json(i)},this.getHasEmail=(e,t)=>{t.json({hasEmail:(0,b.isEmailMaybe)(p.Settings.email.value)})},this.postSystem=async(e,t)=>{const i=e.body,r=[];x().info("post()",{body:e.body}),(0,w.mapTrue)(i.pause,(()=>{(0,u.broadcastPause)(),r.push("Sync was paused")})),(0,w.mapTrue)(i.resume,(()=>{(0,u.broadcastResume)(),r.push("Sync was resumed")})),await(0,w.mapTrue)(i.restartSync,(async()=>{l.StdoutWrite.restartSync(),r.push("Sync restart was requested")})),await(0,w.mapTrue)(i.forceRestartSync,(async()=>{k.Operation.markOpCompleted({name:"forceRestartSync"},{value:"canceled (force-restarted)"}),k.Operation.ensurePendingOp({name:"forceRestartSync"}),l.StdoutWrite.restartSync(),r.push("Sync force-restart was requested")})),await(0,w.mapTrue)(i.rebuildLibrary,(async()=>{(0,T.forceRebuildLibrary)(),l.StdoutWrite.restartSync(),r.push("Library rebuild was requested")})),(0,w.mapTrue)(i.showSyncReports,(()=>{this.openFileService((0,m.syncReportReadme)()),r.push("Opened your sync reports directory")}));const s=(0,_.toS)(i.syncDir);(0,v.notBlank)(s)&&await(0,f.exists)(s)&&(0,c.submitTask_)("syncDir",{nativePath:s}),(0,w.mapTrue)(i.shutdown,(async()=>{const t="requested by "+e.ip;(0,E.shutdown)(t),r.push("Shutdown "+t)})),(0,y.isNotEmpty)(r)?(0,h.sendServerToast)({response:t,toast:{type:"info",text:r.join(". ")}}):(t.status(400),(0,h.sendServerToast)({response:t,toast:{text:"Nothing requested.",type:"warning"}}))}}router(){return s.default.Router().get("/api/system/state",(0,d.wrap)("state",this.getState)).get("/api/system/hasEmail",(0,d.wrap)("hasEmail",this.getHasEmail)).post("/api/system",((e,t)=>(0,h.wrapWithToast)({response:t,f:()=>this.postSystem(e,t)}))).post("/api/system/empty-trash",h.requirePlus,(0,h.requireEnabled)(p.Settings.enableEmptyTrash),F("deletedAt"),O).post("/api/system/remove-assets",h.requirePlus,(0,h.requireEnabled)(p.Settings.enableRemoveAssets),F("excludedAt"),L)}}},47967:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiTagRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(70283),o=i(14889),l=i(80294),u=i(77368),c=i(50080),d=i(43414),h=i(19209),f=i(11944),m=i(75556),p=i(86768),g=i(11254),y=i(48652),v=i(82798),w=i(49374),b=i(30690),S=i(50725),P=(0,n.mkLogger)("ApiTagRouter");function M({name:e,f:t}){return(0,u.wrap)(e,(async(i,r)=>{const s=(0,m.toInt)(i.params.tagId),n=(0,u.extractTagPath)(i.path).map(h.percentDecode),a=(0,u.getSeed)(i),o=(0,u.getFit)(i),l=(0,f.mapNotEmptyOr)(n,(e=>S.Tag.findByIdOrPath(s,e)),(()=>S.Tag.root())),d=null==l?void 0:t(i,l,{tagId:l.id,tagPath:l.path,seed:a,fit:o});return P.debug(e,{result:d,tagPath:n,seed:a,url:i.url}),null==l||null==d?(0,c.send404Toast)({text:"Failed to find tag "+s??n.join("/"),response:r}):(0,u.jsonOrRedirect)(d,r)}))}t.ApiTagRouter=class{router(){return s.default.Router().get("/api/tag*",M({name:"ApiTagRouter.tagGallery",f:this.tagGallery.bind(this)})).get((0,g.nextAssetsUrl)(":tagId",{}),M({name:"ApiTagRouter.tagAssets",f:this.tagAssets.bind(this)})).get((0,g.nextChildTagsUrl)(":tagId",{}),M({name:"ApiTagRouter.childTags",f:this.childTags.bind(this)}))}tagGallery(e,t,i){if(P.debug("tagGallery()",{tag:t}),null==i.seed)return P.debug("tagGallery(): no seed, redirecting..."),(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query));if(d.Settings.fastForwardEmptyTags.valueOrDefault){const i=t.firstNonInterstitialTagId();if(i!==t.id){const t=S.Tag.findById(i);if(null!=t)return(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query),{text:"Skipping to first non-empty child tagโ€ฆ",uuid:"redirect-to-tag",onlyShowUuidOnce:!0,type:"info"})}}const r={fullPath:e.originalUrl,fit:i.fit,...t.toApiTag(),...this.childTags(e,t,i),...this.tagAssets(e,t)};return 0===t.id&&0===b.Asset.shownCount()&&((0,l.isRecentMs)(w.Library.instance()?.start,o.ShortCommandTimeoutMs)?r.startingUp=!0:r.emptyLibrary=!0),r}childTags(e,t,i){const r=(0,m.toInt)((0,v.toS)(e.query.offset))??0,s=(0,m.toInt)((0,v.toS)(e.query.limit))??4;P.debug("childTags() got ",{thisOffset:r,limit:s,query:e.query});const n={tagId:t.id,offset:r,limit:s,seed:i.seed};n.limit=(0,a.firstGt0)(n.limit,4);const o=t.getChildrenCount(),l=0===o?[]:t.getPagedChildren(n);P.debug("childTags()",{crit:n,childTagCount:o,children:l});const u=l.length+r,c=u{const t=e.getRelatedAssetIds({seed:i.seed+e.id,limit:g.ThumbsPerSample});return(0,f.isNotEmpty)(t)?{...e.toApiTag(),assetIds:t}:void 0})));return P.tap({msg:"childTags result",result:{tagId:t.id,childTags:d,childTagCount:o,nextChildTags:c},meta:{nextOffset:u}})}tagAssets(e,t){const i={offset:(0,m.toInt)((0,v.toS)(e.query.offset),{defaultValue:0})},r=t.getPagedAssetIds(i),s=r.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetOpenGraph=void 0;const r=i(13779),s=i(19371),n=i(43414),a=i(27446),o=i(75556);t.getAssetOpenGraph=async function(e,t){if(null==(t=(0,o.toGt0)(t))||!(0,o.gt0)(n.Settings.openGraphTargetWidth.valueOrDefault))return;const i=s.Previews.instance()?.ap(t);if(null==i)return;const l=await i.readInfo();if(null==l)return;const u=[];if((0,a.isVideoMimeType)(l.mimetype)){u.push({property:"og:video",content:e.with({path:"/video/"+t}).toString()});const r=await i.mp4().exists()?"video/mp4":l.mimetype;u.push({property:"og:video:type",content:r},{property:"og:video:width",content:l.width.toString()},{property:"og:video:height",content:l.height.toString()})}else{const s=(await i.widths("fit")??[]).map((e=>({width:e,path:"/img/"+t+"/fit/"+e})));"image/jpeg"===l.mimetype&&s.push({width:l.width,path:"/img/"+t+"/actual"});const a=(0,r.leastBy)(s,(e=>Math.abs(e.width-n.Settings.openGraphTargetWidth.valueOrDefault)));if(null!=a){u.push({property:"og:image",content:e.with({path:a.path}).toString()},{property:"og:image:type",content:"image/jpeg"},{property:"og:image:width",content:a.width.toString()});const t=a.width/(l.width/l.height);(0,o.gt0)(t)&&u.push({property:"og:image:height",content:Math.round(t).toString()})}}return u}},28631:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cspHandler=void 0;const s=r(i(47806)),n=i(4866),a=i(7162),o=i(43414),l=i(83769),u=i(11944),c=(0,n.lazy)((()=>(0,a.mkLogger)("web.WebSecurity")));t.cspHandler=function(e,t,i){(e.secure||(0,l.isHttpsRequest)(e.headers))&&null==o.Settings.upgradeInsecureRequests.value&&(c().warn('Secure https request detected: setting "upgradeInsecureRequests" to true.'),o.Settings.upgradeInsecureRequests.tmpValue=!0);const r=(0,u.compactBlanks)(["'self'",o.Settings.cspDirective.valueOrDefault]),n=(0,u.compactBlanks)(["'self'","'strict-dynamic'",`'nonce-${t.locals.cspNonce}'`,o.Settings.cspDirective.valueOrDefault]);s.default.contentSecurityPolicy({directives:{defaultSrc:["'self'"],scriptSrc:n,styleSrc:r,baseUri:r,formAction:["'self'","https://account.photostructure.com"],objectSrc:["'none'"],upgradeInsecureRequests:o.Settings.upgradeInsecureRequests.valueOrDefault?[]:null},reportOnly:o.Settings.cspReportOnly.valueOrDefault})(e,t,i)}},23163:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requestAssetRepair=t.ImgActualRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(87489),o=i(77368),l=i(50080),u=i(35254),c=i(66776),d=i(75556),h=i(61570),f=i(30690),m=i(89452),p=(0,n.mkLogger)("web.ImgActualRouter");function g(e){return(0,a.submitTask_)("repairAsset",{assetId:e,forceSync:!0,forceRebuildPreviews:!0})}t.ImgActualRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/img/:assetId/:assetFileId/actual(.*)?",(0,o.wrap)("ImgActualRouter.assetImg",this.assetFileImg.bind(this))).get("/img/:assetId/actual(.*)?",(0,o.wrap)("ImgActualRouter.assetImg",this.assetImg.bind(this))).get("/dl/:assetId/:assetFileId",(0,o.wrap)("ImgActualRouter.assetFileImg",this.assetFileImg.bind(this)))}async assetImg(e,t){const i=(0,d.toInt)(e.params.assetId);if(!(0,d.gt0)(i))return(0,l.sendServerToast)({response:t,toast:{text:"Missing assetId in request",type:"warning"},httpStatusCode:400});const r=m.AssetFile.ops().findOneBy({assetId:i,shown:1});return null==r?(p.info("Unknown assetId",e.originalUrl),this.repairAssetLaterAndSendPreview(i,e,t)):this.sendAssetFile(e,t,r)}async assetFileImg(e,t){const i=(0,d.toInt)(e.params.assetId);if(!(0,d.gt0)(i))return(0,l.send404Toast)({response:t,text:'Request was missing "assetId"',httpStatusCode:400});const r=(0,d.toInt)(e.params.assetFileId);if(!(0,d.gt0)(r))return(0,l.send404Toast)({response:t,text:'Request was missing "assetFileId"',httpStatusCode:400});const s=m.AssetFile.ops().findOneBy({id:r,assetId:i});return null==s?(0,l.send404Toast)({response:t,text:"Bad request: no such asset file "+r}):this.sendAssetFile(e,t,s)}async sendAssetFile(e,t,i){const r=i.assetId,s=await i.posixFile_(),n=e.path.split("/").includes("dl")||(0,o.truthyQuery)(e,"dl");if(null==s||await s.isEmpty())return n?(0,l.send404Toast)({response:t,text:"Asset file "+i.uri+" was missing"}):this.repairAssetLaterAndSendPreview(r,e,t);if(n)return p.info("Sending download",{assetId:r,af:i,nativePath:s.nativePath}),t.download(s.nativePath,s.base);const a=e.headers["user-agent"],d=await(0,u.prepFileForBrowser)({nativePath:s.nativePath,userAgent:a,...(0,h.pick)(i,"width","height","sha","mimetype","rotation","mimetype")});return null==d?(p.warn("cannot send file (null result from prepFileForBrowser)",{assetId:r,af:i}),g(r),(0,l.send404Toast)({response:t,text:`Failed to get browser-friendly preview for Asset ${r}.`,details:"I'll try to fix it."})):(p.info("sendAssetFile(): sending supported file: "+d),t.sendFile(d,(e=>(0,c.map)(e,(e=>p.warn("failed to send file",{error:e,assetId:r,af:i}))))))}async repairAssetLaterAndSendPreview(e,t,i){g(e);const r=await this.previews.ap(e).largestFileForReducer("fit");null!=r?i.sendFile(r.nativePath):(f.Asset.ops().upsertOne({id:e,shown:!1}),(0,l.send404Toast)({response:i,text:`Asset ${e} is missing preview images.`,details:"I'll try to fix it, but it will be hidden for now."}))}},t.requestAssetRepair=g},7523:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImgRouter=void 0;const s=r(i(66860)),n=i(49411),a=r(i(57441)),o=i(13779),l=i(7162),u=i(14889),c=i(91464),d=i(29731),h=i(77368),f=i(49441),m=i(43414),p=i(27446),g=i(19209),y=i(36297),v=i(9381),w=i(66776),b=i(75556),S=i(82798),P=i(89452),M=(0,l.mkLogger)("web.ImgRouter");t.ImgRouter=class{constructor(e){this.previews=e}router(){const e=(0,h.wrap)("ImgRouter",this.streamImage.bind(this));return s.default.Router().get("/img/:assetId/:reducer/:width",e)}async streamImage(e,t,i){const r=await this.getFileFromRequest(e,t);if(null!=r){if("setHeader"in t&&(0,b.gt)(r.width,500)){const e=P.AssetFile.dbl.pluckFirstf((e=>e.where({assetId:r.assetId,shown:1}).select("uri")))??"/asset-"+r.assetId+"."+r.file.ext,i=(0,w.map)(e,g.uriToBasename);if(M.debug("streamImage(): AssetFile URI",{shownUri:e,basename:i}),null!=i)try{t.setHeader("X-basename",(0,c.ensureSuffixIgnoreCase)(i,"."+r.file.ext))}catch(e){M.warn("streamImage(): setHeader error",{error:e})}else M.warn("streamImage(): failed to extract basename",{result:r})}return t.sendFile(r.file.nativePath)}}async getFileFromRequest(e,t){const i=e.params,r=(0,b.toInt)(i.assetId),s=v.ReducerNames.getCI(i.reducer)??"fit",l=(0,b.toInt)(i.width);if(null==r||null==s&&null==l)return M.warn("getFileFromRequest(): bad request",{assetId:r,reducer:s,width:l}),void t.sendStatus(y.HttpStatus.BadRequest);const h=this.previews.ap(r),g=h.fileForWidth(s,l);if(await g.exists())return{assetId:r,width:l,file:g};if(m.Settings.placeholderThumbs.valueOrDefault){const e=(0,d.stringShaToBuffer)((0,S.toS)(r)).toString("hex").slice(0,6),t=await(0,f.imageCacheDir_)();if(null==t)return;const i=t.join((0,c.splitEvery)(e,3).join(n.sep)+"-8w.png");return await i.applyIfEmpty_({fn_:t=>(0,a.default)({create:{width:8,height:8,channels:3,background:"#"+e}}).png().toFile(t.nativePath),timeoutMs:u.ShortCommandTimeoutMs}),{assetId:r,width:8,file:i}}const w=await h.widths(s)??[],P=await h.readInfo(),_=(0,p.isImageMimeType)(P?.mimetype)&&(0,p.isMimeTypeSupportedByBrowser)(P?.mimetype)?P?.width:void 0,T=(0,o.leastBy)([...w,_],(e=>(0,b.gt0)(e)&&Math.abs(l-e)));return null==T||T===l?(M.warn("Missing file, and no other widths found",{path:g.nativePath,assetId:r,reducer:s,requestedwidth:l,existingWidth:T}),void t.sendStatus(y.HttpStatus.NotFound)):T===_?(M.debug("redirecting to image actual",{assetId:r,reducer:s,width:l,f:g,existingWidth:T}),void t.redirect(["/img",r,"actual"].join("/"))):(M.debug("replacing requested width",{assetId:r,reducer:s,width:l,f:g,existingWidth:T}),void t.redirect(["/img",r,s,T].join("/")))}}},1807:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.siteManifest=t.ManifestRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(77368),l=i(22189),u=i(43586),c=i(43414),d=(0,n.lazy)((()=>(0,a.mkLogger)("web.ManifestRouter")));async function h({requestUri:e,id:t}){return{id:t??"com.photostructure",name:"PhotoStructure",start_url:e.with({path:c.Settings.defaultHomepagePath.valueOrDefault,query:null,fragment:null}).toString(),display:"fullscreen",icons:[{src:"/192.png",sizes:"192x192",type:"image/png"},{src:"/512.png",sizes:"512x512",type:"image/png"},{src:"/images/logo-gradient.svg",sizes:"any",type:"image/svg+xml"}],theme_color:"#845BAC",background_color:"#845BAC"}}t.ManifestRouter=class{router(){return s.default.Router().get("/site.webmanifest",(0,o.wrap)("SiteManifest",this.siteManifest.bind(this)))}async siteManifest(e,t,i){const r=await((0,u.LibraryUIDStore)()?.readUid_().catch((()=>{}))),s=(0,l.requestedUri)(e,{protocol:"http",host:c.Settings.hostname.value}),n=await h({id:r,requestUri:s});d().debug("siteManifest",n),t.type("application/manifest+json").json(n)}},t.siteManifest=h},81169:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAssetFileRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(72612),l=i(75556),u=i(89452),c=(0,n.mkLogger)("web.OpenAssetFileRouter");t.OpenAssetFileRouter=class{constructor(e){this.openFileService=e}router(){return s.default.Router().get("/api/openAssetFile/:assetFileId",(0,a.wrap)("OpenAssetFileRouter.assetFile",this.assetFile.bind(this)))}async assetFile(e,t){if(c.info("assetFile(): got request",{url:e.originalUrl,ip:e.ip}),!(0,o.isLocalhost)(e.ip))return c.info("Non-localhost request",{url:e.originalUrl,ip:e.ip}),t.sendStatus(400);const i=(0,l.toInt)(e.params.assetFileId);if(!(0,l.gt0)(i))return c.info("Missing assetFileId",e.originalUrl),t.sendStatus(400);const r=u.AssetFile.ops().findOneBy({id:i});if(null==r)return c.info("Invalid assetFileId",e.originalUrl),t.sendStatus(400);const s=await r.posixFile_();return null==s||await s.clear().notExists()?(c.info("File not found",{url:e.originalUrl,af:r,file:s}),t.sendStatus(400)):(c.info("Requesting openFileService("+s.nativePath+")...",{url:e.originalUrl,ip:e.ip}),this.openFileService(s.nativePath),t.sendStatus(204))}}},51706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PingRouter=void 0;const s=r(i(66860)),n=i(4691),a=i(36297);t.PingRouter=class{router(){return s.default.Router().get("/ping",((e,t)=>t.sendStatus((0,n.ending)()?a.HttpStatus.ServiceUnavailable:a.HttpStatus.OK)))}}},64104:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getPlansLicense=t.getPlansBilling=t.getPlansActivate=t.getPlansPick=t.PlansRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(2023),l=i(42041),u=i(77368),c=i(22189),d=i(13700),h=i(59714),f=i(43414),m=i(39938),p=i(88491),g=i(39784),y=(0,n.lazy)((()=>(0,a.mkLogger)("web.PlansRouter")));async function v(e,t){return await S({req:e,res:t,remotePath:"/plans/pick"})}async function w(e,t){return await S({req:e,res:t,remotePath:"/",params:{skipIndex:!0}})}async function b(e,t){return await S({req:e,res:t,remotePath:"/"})}async function S({req:e,res:t,remotePath:i,params:r={}}){const s=(0,c.requestedUri)(e).with({path:"/plans/license"}),n=await(0,d.sids)({timeoutMs:4*p.secondMs}),a=new URL("https://account.photostructure.com"+i);return a.searchParams.append("version",l.version),a.searchParams.append("uids",n.join(",")),(0,m.mapNotBlank)(f.Settings.coupon.value,(e=>a.searchParams.append("coupon",e))),a.searchParams.append("redirectToLibraryUrl",s.toString()),(0,o.mapEntries)(r,((e,t)=>a.searchParams.append(e,t))),y().info("GET /plans/pick",{redirectToLibraryUrl:s.toString()}),t.redirect(a.toString())}async function P(e,t){try{(0,m.mapNotBlankOr)(e.query.license,(async e=>{await(0,h.writeLicense)(e,3*p.secondMs),y().info("getPlansLicense(): Saved new license",e)}),(()=>{y().info("getPlansLicense(): no license in request",e.originalUrl)}))}catch(t){y().error("getPlansLicense(): Failed to save license",{err:t,url:e.originalUrl})}const i=(0,m.notBlankOr)((0,g.toA)(e.query.then)[0],"/settings");y().info("getPlansLicense(): redirecting to "+i),t.redirect(i)}t.PlansRouter=class{router(){return s.default.Router().get("/plans/pick",(0,u.wrap)("GET /plans/pick",v)).get("/plans/activate",(0,u.wrap)("GET /plans/activate",w)).get("/plans/billing",(0,u.wrap)("GET /plans/billing",b)).get("/plans/license",(0,u.wrap)("GET /plans/license",P))}},t.getPlansPick=v,t.getPlansActivate=w,t.getPlansBilling=b,t.getPlansLicense=P},79669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressProvider=void 0;const r=i(5712),s=i(97742),n=i(24945),a=i(51498),o=i(4866),l=i(7162),u=i(46852),c=i(79403),d=i(51053),h=i(67220),f=i(11944),m=i(38625),p=i(88491),g=i(1429),y=i(21040),v=i(42313),w=i(82798),b=i(30690),S=i(89452),P=i(65548),M=(0,o.lazy)((()=>(0,l.mkLogger)("web.ProgressWithAssets")));t.ProgressProvider=class{constructor(e=10){this.maxLen=e,this.priorRecentAssets=new a.FifoCache(15,15*p.secondMs),this.testProgressStatesByVolume=new Map}async updates(){return(0,u.thenMap)(this.states(),(e=>({states:e})))}async states(){if((0,h.isPaused)())return[{volume:"โธ",state:"paused",hed:"Paused",dek:["Processing is paused. Resume via the navigation menu"+(d.isElectron?" or the system tray menu":"")+"."],recentAssetIds:[]}];const e=await c.HealthCheck.errorResults();if((0,f.isNotEmpty)(e))return M().warn("health check is failing",{errors:e}),[{volume:"โš ๏ธ",state:"paused",hed:"Health checks failed. Click for details.",dek:(0,f.uniq)((0,g.flatten)(e.map((e=>e.msg)))),recentAssetIds:[]}];const t=this.recentProgress();return M().debug("recentProgressWithAssets()",t),(0,f.isEmpty)(t)&&(0,m.isTrue)(s.env.TEST_PROGRESS)?this.testProgress():t}recentProgress(){const e=P.Progress.ops().allf((e=>e.where("updatedAt",">",Date.now()-p.minuteMs).whereNotNull("state").orderBy("volume")));(0,f.filterInPlace)(e,(e=>!(!(0,r.pidExists)(e.pid)&&"done"!==e.state&&(M().warn("Incomplete progress is from a dead process",{progress:e}),e.upsert({state:null}),1))));const t=[],i=new Set;for(const r of e){const e="done"===r.state,s=r.toSyncState(),n=this.priorRecentAssets.get((0,w.toS)(r.id))??[];if(!e){const e=((0,v.noRecentAssetIdsProgress)(s)?[]:S.AssetFile.recentAssetIdsByUriRoot((0,v.isRebuildProgress)(s)?void 0:s.uri,p.minuteMs,this.maxLen+i.size)).filter((e=>!i.has(e)&&!n.includes(e)));(0,f.isNotEmpty)(n)&&e.length>=this.maxLen&&e.splice(0,this.maxLen-1),n.unshift(...e),n.length=this.maxLen,this.priorRecentAssets.set((0,w.toS)(r.id),n);for(const e of n)i.add(e)}t.push({...s,recentAssetIds:n})}return t}async testAssetIds(e){const t=(0,y.getOrSet)(this.testProgressStatesByVolume,e,(()=>new n.BoundedList(this.maxLen))),i=b.Asset.dbl.pluckFirstf((e=>b.Asset.shownUnhidden(e).select("id").orderByRaw("random()").first()));return null!=i&&t.push(i),t.toA()}async testProgress(){const e=Math.round(Date.now()/(30*p.secondMs))%3,t=(d.isWin?["C:","D:","E:"]:["/","/home/bob/pictures","/mnt/nas"])[e];return[{volume:t,state:"processing",hed:"Processing, about 32 minutes remaining",dek:["Processing C:\\Users\\mrm\\Pictures\\20161214-pixel\\DCIM\\Camera\\IMG_20160903_090736.jpg","Processed 445 images and videos. 1,386 remain to be processed."],completePct:40,incompletePct:25,scanningPct:35,recentAssetIds:await this.testAssetIds(t)}]}}},47458:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.render=void 0;const r=i(9678),s=i(4866),n=i(7162),a=i(19658),o=i(69060),l=i(72612),u=i(15203),c=i(51053),d=i(43414),h=i(67220),f=i(38625),m=i(20636),p=i(39607),g=i(50725),y=(0,s.lazy)((()=>(0,n.mkLogger)("web.PugHelpers")));t.render=async function(e,t,i,s={}){const n=e.headers["user-agent"];t.setHeader("Feature-Policy","autoplay 'self'");const v=[],w=!0===n?.toLowerCase().includes("electron")&&(0,l.isLocalhost)(e.ip)||(0,f.isTrue)(e.query.electron);w&&(v.push("electron"),c.isMac?v.push("mac"):c.isWin?v.push("win"):c.isLinux&&v.push("linux")),a.isDev&&v.push("is-dev"),(0,p.isChrome)(n)?v.push("chrome"):(0,p.isSafari)(n)?v.push("safari"):(0,p.isFirefox)(n)&&v.push("firefox"),(0,p.isIphone)(n)?v.push("iphone"):(0,p.isIpad)(n)&&v.push("ipad"),(0,h.isPaused)()&&v.push("is-paused"),(0,l.isLocalhost)(e.ip)&&!(0,u.isDocker)()&&v.push("is-localhost");try{!0===await(0,m.thenOrTimeout)((0,o.p)(),250)&&v.push("is-plus")}catch{}d.Settings.enableArchive.valueOrDefault&&v.push("enable-archive"),d.Settings.enableDelete.valueOrDefault&&v.push("enable-delete"),d.Settings.enableRemove.valueOrDefault&&v.push("enable-remove");const b={bodyClass:v.join(" "),isDocker:(0,u.isDocker)(),isElectron:w,isDev:a.isDev,nonce:t.locals.cspNonce,hasEmail:d.Settings.email.hasValue(),...s};y().debug("render()",{ua:n,template:i,options:b,headers:e.headers}),t.render(i,{rootTags:null==g.Tag.db()?void 0:g.Tag.roots(),title:(0,r.AppName)(),...b})}},69475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SSEHealthRouter=void 0;const r=i(34996),s=i(41749),n=i(79403),a=i(232),o={event:"done",data:{done:!0}};function l(e){return null==e?void 0:{event:"result",data:e}}class u extends s.ServerSentEventsRouter{constructor(){super("/sse/health")}firstEvents(e,t){return this.sendResults(t),[]}async sendResults(e){const t=[],i=[];i.push(n.HealthCheck.summary());for(const e of n.HealthCheck.all()){const r=e.toResultSync();i.push(r),("pending"===r.level||e.isStale())&&t.push(e)}e.write((0,a.mkEventStream)(...i.map(l))),this.logger.debug("sendResults (sync)",{pending:t.map((e=>e.id)),resolved:i.map((e=>e.id))});for await(const i of r.Deferred.toAsyncIterable(t.map((e=>e.result())))){const t=(0,a.mkEventStream)(l(i),l(n.HealthCheck.summary()));this.logger.debug("sendResults (async)",{result:i,chunk:t}),e.write(t)}e.write((0,a.mkEventStream)(l(n.HealthCheck.summary()),o),(()=>this.endStream(e)))}}t.SSEHealthRouter=u},35818:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsRouter=void 0;const s=r(i(66860)),n=i(42748),a=i(49411),o=i(7162),l=i(19658),u=i(38307),c=i(82341),d=i(18226),h=i(79015),f=i(77368),m=i(98462),p=i(46517),g=i(69060),y=i(15203),v=i(51053),w=i(83773),b=i(43414),S=i(82041),P=i(57310),M=i(11944),_=i(39938),T=i(38625),E=i(88491),D=i(19067),k=i(87748),x=i(66776),C=i(61570),F=i(20636),I=i(17078),A=i(39784),O=i(82798),L=i(37831),R=i(4958),N=i(47458),B=(0,o.mkLogger)("web.SettingsRouter");t.SettingsRouter=class{constructor(e=c.libraryDirPosixFile,t=L.librarySettings,i=R.suggestedLibraryDirs){this.libraryDir=e,this.settings=t,this.libraryDirSuggester=i}router(){return s.default.Router().get("/setting",((e,t)=>t.redirect("/settings"))).get("/settings",(0,f.wrap)("GET /settings",this.get.bind(this))).post("/settings",(0,f.wrap)("POST /settings",this.post.bind(this)))}async get(e,t){const{err:i,libraryDir:r}=e.body;try{await(0,S.readSettings)();const s=await(0,F.thenOrTimeoutError)(this.requestSettings(e),1e3);return await(0,F.thenOrTimeoutError)(this.renderSettings(e,t,s,r,i),1e3)}catch(e){return B.warn("requestSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}}async renderSettings(e,t,i,r,s){(0,h.ee)().emit("clearCache");let o=await this.libraryDirSuggester();if(null==(0,O.toS)(s).match(/choose a different directory/i)){const e=await R.SuggestedLibraryDir.for(r);null!=e&&o.unshift(e)}(0,M.isEmpty)(o)&&(o=void 0);const u=this.libraryDir();(0,_.blank)(s)&&(0,y.isDocker)()&&(null==u||await u.isNotDirectory())&&(s=`PS_LIBRARY_DIR, ${u?.nativePath??"/ps/library"}, doesn't exist: please add it as a bind mount.`);const c=await(0,p.getVideoToolDetails_)(l.isProd?void 0:e.query),C=await(0,d.picturesDir)(),F=await(0,g.b)(),A={err:s,...i,autoUpdateCheck:i.autoUpdateCheck??!0,allowUserAgent:i.allowUserAgent??!0,reportErrors:i.reportErrors??!0,welcome:(0,x.mapOr)(l.isProd?void 0:e.query.welcome,T.isTrue,(()=>!(0,S.libraryHasSettings)())),title:null==u?"Welcome!":"Settings",videoToolDetails:c,picturesPath:C,jsonScanPaths:(0,x.map)(b.Settings.scanPaths.value,k.stringify),delimiter:a.delimiter,exampleScanPath:[C,v.isWin?"D:\\PHOTOS":v.isMac?"/Volumes/External HD/Pictures":"/mnt/nas/homes/photos"].join(a.delimiter),currentLibraryDir:(0,x.map)(u,(e=>e.nativePath)),minFreeAvailable:(0,I.fmtBytes)(b.Settings.minDiskFreeGb.valueOrDefault*I.GB),suggestedLibraryDirs:o,samplePath:(0,w.pathToLibraryAsset)(n.DateTime.now(),m.BaseFile.for("photo.jpg")).join(a.sep),subTier:await(0,g.t)(),subTrial:(0,T.isTrue)(F?.l?.trial),subEmail:F?.l?.sub,subExpiresInDuration:(0,x.map)(F?.l?.exp,(e=>(0,D.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,x.map)(F?.l?.exp,E.fmtIsoDate),userAgent:await(0,P.systemUserAgent)()};B.info("rendering settings",A),(0,f.disableCache)(t),await(0,N.render)(e,t,"settings",A)}async post(e,t){const i=e.body,r=(0,_.toNotBlank)("libraryDirCustom"===i.libraryDirRadio?i.libraryDir:i.libraryDirRadio),s=i=>this.renderSettings(e,t,c,r,i),n=r??b.Settings.libraryDir.valueOrDefault;if((0,_.blank)(n))return s("Please choose a directory for your library.");const o=(0,a.resolve)(n),c=await this.requestSettings(e);B.info("POST",{libraryDir:o,settings:c,body:i}),l.isTest&&(0,u.stdoutWrite)({post:i,settings:c,method:e.method,libraryDir:o});try{const e=await(0,L.saveLibrarySettings)(o,c);if("error"in e)return B.info("error saving library settings",{result:e}),s(e.error);B.info("saved library settings. Waiting for bookkeeping to finish...",e),await e.ready,B.info("ready. Redirecting to /splash...",e)}catch(e){return s(e)}return t.redirect("/splash")}async requestSettings(e){const{scan:t,scanPath:i,copyAssets:r,autoUpdateCheck:s,allowUserAgent:n,reportErrors:a}=e.body,o=this.settings();return(0,_.notBlank)(t)&&(o.scanAllDrives="scanAllDrives"===t,o.scanPath=(0,M.compactBlanks)((0,A.toA)(i))),(0,_.notBlank)(r)&&(o.copyAssets="copyEnabled"===r),o.allowUserAgent=(0,T.toBoolean)(n),o.autoUpdateCheck=(0,T.toBoolean)(s),o.reportErrors=(0,T.toBoolean)(a),B.info("requestSettings()",{req_body:(0,C.pick)(e.body,"scan","scanPath","copyAssets","autoUpdateCheck","allowUserAgent","reportErrors"),result:o}),(0,L.librarySettings)(o)}}},71885:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SpaRouter=void 0;const s=r(i(66860)),n=i(77368),a=i(22189),o=i(16715),l=i(47458);t.SpaRouter=class{router(){const e=(0,n.wrap)("SpaRouter",this.get.bind(this));return s.default.Router().get("/tag*",e).get("/asset/:assetId",(0,n.wrap)("SpaRouter.Asset",this.getAsset.bind(this))).get("/search",e)}async getAsset(e,t,i){const r=await(0,o.getAssetOpenGraph)((0,a.requestedUri)(e),e.params.assetId);return(0,l.render)(e,t,"app",null==r?{}:{meta:r})}get(e,t,i){if(!e.path?.startsWith("/tag")||null!=(0,n.getSeedOrRedirect)(e,t))return(0,l.render)(e,t,"app",{})}}},39787:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(11944),l=i(66776),u=i(75556),c=i(89452),d=(0,n.mkLogger)("web.VideoRouter");t.VideoRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/video/:assetId",(0,a.wrap)("VideoRouter",this.videoImage.bind(this)))}async videoImage(e,t,i){const r=e.params,s=(0,u.toInt)(r.assetId);if(!(0,u.gt0)(s))return d.warn("Malformed request (missing assetId)",{params:e.params}),t.sendStatus(400);const n=this.previews.ap(s).mp4();if(await n.exists())return d.info("streaming transcoded video",n),t.sendFile(n.nativePath);const a=c.AssetFile.ops().findBy({assetId:s,shown:1});if((0,o.isEmpty)(a))return d.warn("Malformed request (bad assetId)",{params:e.params}),t.sendStatus(400);const h=a[0],f=await(0,l.map)(h,(e=>e.posixFile_()));return null!=f&&h.isVideo&&await f.exists()?t.sendFile(f.nativePath):(d.warn("Shown assetFile isn't a video",h),t.sendStatus(400))}}},21625:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebService=void 0;const s=r(i(66860)),n=r(i(47806)),a=r(i(6005)),o=r(i(97742)),l=i(4866),u=i(7162),c=i(70283),d=i(38307),h=i(4691),f=i(2126),m=i(46852),p=i(53525),g=i(79141),y=i(28941),v=i(53235),w=i(77659),b=i(22189),S=i(9786),P=i(50080),M=i(1597),_=i(98250),T=i(27175),E=i(57294),D=i(79403),k=i(13700),x=i(38786),C=i(94845),F=i(43414),I=i(82041),A=i(53719),O=i(46573),L=i(17679),R=i(36297),N=i(29144),B=i(43947),j=i(66776),z=i(61715),V=i(23022),W=i(48652),U=i(49374),q=i(27242),H=i(27579),G=i(20990),$=i(39946),J=i(36389),K=i(86840),Y=i(16654),X=i(47576),Z=i(6757),Q=i(40687),ee=i(34312),te=i(47967),ie=i(28631),re=i(23163),se=i(7523),ne=i(1807),ae=i(81169),oe=i(51706),le=i(64104),ue=i(79669),ce=i(69475),de=i(35818),he=i(71885),fe=i(39787),me=i(26518),pe=i(63986);function ge(e,t){t.endsWith(".js")&&e.setHeader("Content-Type","application/javascript")}const ye=(0,u.mkLogger)("web.WebService"),ve=e=>(0,E.showFileInFolder)(_.PosixFile.for(e));t.WebService=class{constructor(){this.setup=(0,l.lazy)((async()=>{if(ye.debug("setup(): started"),o.default.on("SIGPIPE",(e=>{ye.info("Caught SIGPIPE",e)})),F.Settings.libraryDir.watchLater((()=>Me.unset())),await(0,m.rejected)(this.service.ready))return void ye.error("setup(): failed, service.ready was rejected");await(0,N.setupShimDelegates)();const e=this.app;if(e.use((new w.RequestLogger).router),e.use(((e,t,i)=>{t.locals.cspNonce=a.default.randomBytes(16).toString("hex"),i()})),F.Settings.trustProxy.hasValue()){const t=F.Settings.trustProxy.value,i="true"===t||"false"!==t&&(0,c.mapGte0Or)(t,(e=>e),t);e.set("trust proxy",i),ye.info("trust proxy set",{value:i})}if(e.use(P.expressErrorHandlerWithToast),(0,q.sentryEnabled)())try{e.use(i(9856).Handlers.requestHandler())}catch(e){ye.warn("Failed to initialize Sentry requestHandler",{error:e})}if(F.Settings.disabledHelmetMiddleware.valueOrDefault.includes(L.HelmetPlugins.all))ye.warn("DANGER: disabledHelmetMiddleware includes 'all': not enabling any Helmet middleware.");else{F.Settings.disabledHelmetMiddleware.valueOrDefault.includes(L.HelmetPlugins.contentSecurityPolicy)||e.use(ie.cspHandler);const t={contentSecurityPolicy:!1};for(const e of F.Settings.disabledHelmetMiddleware.valueOrDefault.filter((e=>e!==L.HelmetPlugins.all)))t[e]=!1;e.use((0,n.default)(t))}e.use(b.addXSettingsHandler),e.use(pe.json()),e.use(pe.urlencoded({extended:!1}));const t=T.ProjectPath.Public(),r=T.ProjectPath.Views();if(ye.info("setup()",{libraryDir:F.Settings.libraryDir.valueOrDefault,publicRoot:t,viewsRoot:r}),I.libraryHasSettings.watch((()=>e.set("etag",(0,I.libraryHasSettings)()))),e.set("views",r),e.set("view engine","pug"),e.use((new oe.PingRouter).router()),e.use((new y.ApiHealthRouter).router()),e.use((0,M.viewRouter)({path:"/splash",view:"splash"})),e.use((new Q.ApiSplashRouter).router()),e.use((0,M.viewRouter)({path:"/health",view:"health"})),e.use((new ce.SSEHealthRouter).router()),e.use((new K.AdminPostRouter).router()),e.get("/status",((e,t)=>t.redirect("/health"))),e.use(await(0,S.serveStaticGz)(t)),e.use(s.default.static(t,{setHeaders:ge})),e.use((new J.AboutRouter).router()),e.use((new me.WelcomeRouter).router()),e.use((new le.PlansRouter).router()),e.use(Pe()),(0,C.isPacked)()||(e.use("/die",((e,t)=>{ye.info("/die was requested",{url:e.originalUrl}),t.sendStatus(R.HttpStatus.Accepted),(0,f.exit)({reason:"/die",status:1})})),e.use("/test-sentry",((e,t)=>{(0,H.sendToSentry)(new g.WrappedError("test message sent to sentry at "+new Date)),t.sendStatus(R.HttpStatus.Accepted)}))),e.use(((e,t,i)=>(0,h.ending)()?(ye.info("ending(): returning 500",{requestUri:(0,b.requestedUri)(e)}),t.sendStatus(500)):function(){const e=D.HealthCheck.runState();switch(e){case z.RunStates.loading:return we();case z.RunStates.welcome:return Se();case z.RunStates.ready:return Me()??Me.refresh()??be();case z.RunStates.failed:return be();default:throw new V.UnreachableCaseError(e)}}()(e,t,i))),(0,q.sentryEnabled)())try{e.use(i(9856).Handlers.errorHandler())}catch(e){ye.warn("Failed to initialize Sentry error handling",{error:e})}const l=F.Settings.httpPort.valueOrDefault,u=F.Settings.exposeNetworkWithoutAuth.valueOrDefault,v=U.Library.instance();null!=v?D.HealthCheck.addLoadingMsg("Loading library..."):D.HealthCheck.addLoadingMsg("Starting...");const _=async()=>{ye.info("setup(): http server callback",{httpPort:l,expose:u});const e=[F.Settings.httpPort];null!=v&&e.push(F.Settings.libraryDir),(0,d.stdoutWriteSettings)(...e),null==v?((0,k.sids)((0,A.commandTimeoutMs)()).catch((e=>ye.warn("failed to prefetch sids",e))),(0,O.volumes)().catch((e=>ye.warn("failed to prefetch volumes",e)))):(await v.ready,Me.unset()),await(0,$.libraryHealthCheckSetup)(),await D.HealthCheck.awaitSettled(),null!=v&&d.StdoutWrite.restartSync()},E=u?e.listen(l,_):e.listen(l,F.Settings.localhost.valueOrDefault,_);return E.on("error",(e=>{ye.warn("http.server.onError()",e),"EADDRINUSE"===e.code&&(0,f.exit)({reason:"Port "+l+" is already in use: is PhotoStructure already running?"+p.FatalErrorFlag+p.DoNotSendErrorFlag+p.WebFatalErrorFlag,error:e,status:3})})),new x.EndableServer("http.WebService",E)})),this.app=(0,s.default)(),this.service=new G.Service({name:"web"}),this.setup()}};const we=(0,l.lazy)((()=>(0,v.redirectRouter)("/splash"))),be=(0,l.lazy)((()=>(0,v.redirectRouter)("/health"))),Se=(0,l.lazy)((()=>(0,v.redirectRouter)("/welcome"))),Pe=(0,l.lazy)((()=>(new de.SettingsRouter).router())),Me=(0,l.lazy)((()=>{const e=U.Library.instance();if(null==e)return ye.warn("libraryRouter invoked before library is set up."),void setImmediate((()=>Me.unset()));ye.info("Setting up library router for "+(0,j.map)(e,(e=>e.rootDir)));const t=e.previews(),i=new ue.ProgressProvider,r=s.default.Router();return r.use((new ne.ManifestRouter).router()),r.use(new ee.ApiSystemRouter(ve).router()),r.use((new te.ApiTagRouter).router()),r.use(new Y.ApiAssetRouter(t).router()),r.use((new Z.ApiSearchRouter).router()),r.use((new he.SpaRouter).router()),r.use(new ae.OpenAssetFileRouter(ve).router()),r.use(new re.ImgActualRouter(t).router()),r.use(new se.ImgRouter(t).router()),r.use(new fe.VideoRouter(t).router()),r.use(new X.ProgressRouter(i).router()),r.use("/",((e,t)=>{ye.debug("in root route",{res_headersSent:t.headersSent,res_headers:t.getHeaders()}),t.redirect(302,(0,W.mkHomeFullPath)(e.query))})),r}));(0,B.later)((()=>{F.Settings.libraryDir.watchLater((()=>Me.unset()))}))},26518:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WelcomeRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(79403),l=i(69060),u=i(43414),c=i(36297),d=i(4958),h=i(64104),f=i(47458);t.WelcomeRouter=class{constructor(){this.logger=(0,n.mkLogger)("WelcomeRouter")}router(){return s.default.Router().get("/welcome",(0,a.wrap)("GET /welcome",this.get.bind(this))).post("/welcome",(0,a.wrap)("POST /welcome",this.post.bind(this)))}async get(e,t){return"welcome"!==o.HealthCheck.runState()?t.redirect(c.HttpStatus.Found,"/"):((0,d.suggestedLibraryDirs)(),(0,f.render)(e,t,"welcome",{}))}async post(e,t){return!u.Settings.pickPlanOnWelcome.valueOrDefault||await(0,l.p)()?t.redirect("/settings"):(0,h.getPlansPick)(e,t)}}},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},63986:e=>{"use strict";e.exports=require("body-parser")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},66860:e=>{"use strict";e.exports=require("express")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},47806:e=>{"use strict";e.exports=require("helmet")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},34235:e=>{"use strict";e.exports=require("moo")},50764:e=>{"use strict";e.exports=require("nearley")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")},71017:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=72316);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={74485:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},79551:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(74485),{decode:n}=i(87536),a=i(91225);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},15880:(e,t,i)=>{const r=i(79551);e.exports={decode:r}},77308:(e,t,i)=>{const r=i(62705);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},88277:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(74485),s=i(62705);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},42417:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},25054:(e,t,i)=>{const r=i(10315);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},55589:(e,t,i)=>{const r=i(77308),s=i(10315);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},70067:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},97362:(e,t,i)=>{const r=i(39084),{PasetoInvalid:s}=i(74485),n=i(88277),{decode:a}=i(87536),o=i(91225);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},45112:(e,t,i)=>{const r=i(6113),s=i(16464),n=i(97540),a=i(45018),{PasetoDecryptionFailed:o}=i(74485),l=i(156),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},45445:(e,t,i)=>{const{KeyObject:r}=i(6113);let{isKeyObject:s}=i(35740);s||(s=e=>null!=e&&e instanceof r),e.exports=s},10315:e=>{e.exports=e=>!!e&&e.constructor===Object},44071:(e,t,i)=>{const{PasetoNotSupported:r}=i(74485);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},62705:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},45018:(e,t,i)=>{const{encode:r}=i(87536);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},97540:(e,t,i)=>{const r=i(44071);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},91225:(e,t,i)=>{const{PasetoInvalid:r}=i(74485),{strict:s}=i(39084),n=i(10315);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},69946:(e,t,i)=>{const{sign:r}=i(45112),s=i(97540),n=i(45018);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},29744:(e,t,i)=>{const{createSecretKey:r}=i(6113),s=i(45445);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},156:(e,t,i)=>{const{timingSafeEqual:r}=i(6113),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},80094:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(74485),{verify:s}=i(45112),n=i(97540),{pre:a}=i(97362);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91144:(e,t,i)=>{const r=i(74485),s=i(37794),n=i(16582),a=i(76625),o=i(74421),{decode:l}=i(15880);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},34089:(e,t,i)=>{const{"v1.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v1.local"),{pre:n,post:a}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},15490:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v1.local"),n=i(55589),{"v1.local-encrypt":a}=i(45112);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},37794:(e,t,i)=>{const r=i(54773),s=i(76331),n=i(15490),a=i(34089),o=i(17053);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},17053:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},54773:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(6113),a=i(25054),o=i(55589),l=i(69946),u=i(45445);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},76331:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(6113),a=i(80094),o=i(45445),{post:l}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},16582:(e,t,i)=>{const r=i(83985),s=i(49172),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(42421);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},42421:(e,t,i)=>{const r=i(39084),s=i(6113),{promisify:n}=i(16464),{PasetoNotSupported:a}=i(74485),o=i(45445),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},83985:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(69946),{_checkPrivateKey:a}=i(42421),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},49172:(e,t,i)=>{const r=i(80094),{_checkPublicKey:s}=i(42421),{post:n}=i(97362),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},5817:(e,t,i)=>{const{"v3.local-decrypt":r}=i(45112),s=i(29744).bind(void 0,"v3.local"),n=i(42417),{pre:a,post:o}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},12596:(e,t,i)=>{const r=i(25054),s=i(29744).bind(void 0,"v3.local"),n=i(55589),a=i(42417),{"v3.local-encrypt":o}=i(45112);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},76625:(e,t,i)=>{const r=i(38681),s=i(58271),n=i(12596),a=i(5817),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(93002);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},93002:(e,t,i)=>{const r=i(6113),{promisify:s}=i(16464),{PasetoNotSupported:n}=i(74485),a=i(45445),o=i(70067),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},38681:(e,t,i)=>{const{createPrivateKey:r}=i(6113),s=i(25054),n=i(55589),a=i(42417),o=i(69946),l=i(45445),{bytesToKeyObject:u}=i(93002),c=i(70067);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},58271:(e,t,i)=>{const{createPublicKey:r}=i(6113),s=i(42417),n=i(80094),a=i(45445),{bytesToKeyObject:o}=i(93002),l=i(70067),{post:u}=i(97362);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},74421:(e,t,i)=>{const r=i(54294),s=i(5816),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(80244);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},80244:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(42421);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},54294:(e,t,i)=>{const r=i(25054),s=i(55589),n=i(42417),a=i(69946),{_checkPrivateKey:o}=i(80244),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},5816:(e,t,i)=>{const r=i(42417),s=i(80094),{_checkPublicKey:n}=i(80244),{post:a}=i(97362),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},9678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(4866),s=i(19658),n=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+(s.isProd?"":`-${s.nodeEnv}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},13779:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const r=i(11944),s=i(14439),n=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const s=r(i(97742)),n=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),b=i(53525),S=i(49379),P=i(17875),M=i(51053),_=i(43414),T=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,T.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:s.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),r.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),r.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),r.on("fatalError",(e=>{this.onError("on(fatalError)"+b.FatalErrorFlag,e)})),r.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),r.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),r.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,T.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,n.lazy)((()=>(0,d.mkLogger)(t)))}}},59390:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(55413);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toArray(){return this.vacuum(),this.sortedArray.store}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},24945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(75556);class s{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,r.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,r.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=s},83486:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(82798),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(97461);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},32843:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=n(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const r=i(21941);let s=!(0,r.noColor)();function n(e,t){return i=>s?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){s=e??!(0,r.noColor)()},t.reset=n(0,0),t.bold=n(1,22),t.dim=n(2,22),t.italic=n(3,23),t.underline=n(4,24),t.overline=n(53,55),t.inverse=n(7,27),t.hidden=n(8,28),t.strikethrough=n(9,29),t.black=n(30,39),t.red=n(31,39),t.green=n(32,39),t.yellow=n(33,39),t.blue=n(34,39),t.magenta=n(35,39),t.cyan=n(36,39),t.lightGrey=n(37,39),t.darkGrey=n(90,39),t.redBright=n(91,39),t.greenBright=n(92,39),t.yellowBright=n(93,39),t.blueBright=n(94,39),t.magentaBright=n(95,39),t.cyanBright=n(96,39),t.white=n(97,39),t.bgBlack=n(40,49),t.bgRed=n(41,49),t.bgGreen=n(42,49),t.bgYellow=n(43,49),t.bgBlue=n(44,49),t.bgMagenta=n(45,49),t.bgCyan=n(46,49),t.bgLightGrey=n(47,49),t.bgDarkGrey=n(100,49),t.bgRedBright=n(101,49),t.bgGreenBright=n(102,49),t.bgYellowBright=n(103,49),t.bgBlueBright=n(104,49),t.bgMagentaBright=n(105,49),t.bgCyanBright=n(106,49),t.bgWhite=n(107,49)},94383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(59694),s=i(75556),n=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},71215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},54883:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(4866),s=i(9678),n=i(15203),a=i(51053);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},70403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(24603),s=i(66776),n=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(39653),s=i(4866),n=i(98250);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},39653:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(4866),s=i(40786),n=i(3955);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},82128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(66776),s=i(70208),n=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return r(this,i,"f")}halt(){s(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},37410:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(4866);t.isSuspended=(0,r.lazy)((()=>!1))},79378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(93977),s=i(87748);var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},12374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(889),s=i(42748),n=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},4866:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,n.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(4866),s=i(74269),n=i(78109);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},48783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(11944),s=i(66776),n=i(39784),a=i(13779);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(87748),s=i(51498);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(97742),s=i(75556),n=i(17078),a=i(6667);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},21941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const r=i(38625);t.noColor=function(){return(0,r.toBoolean)(process.env.PS_LOG_COLOR)??(0,r.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const s=r(i(97742)),n=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&s.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=s.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},46954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(43383),s=i(49849);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},70283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(11944),s=i(88491),n=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[r,s]of(0,u.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,u.keys)(e))if(r[n]=t(n,e[n]),s++,(0,l.gt)(s,i))break;return r},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,n.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(17718),s=i(87561),n=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},93813:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=3},75405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(5712),s=i(39784),n=i(21142);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const s=i(5712),n=r(i(17718)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),b=i(99869),S=i(91641),P=i(95557),M=i(4691),_=i(46852),T=i(46027),E=i(4586),D=i(17875),k=i(98462),x=i(25015),C=i(3955),F=i(51053),I=i(71663),A=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),O=10*c.secondMs;function L(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,x.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))A().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,l.isEmpty)(s))return A().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,w.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){A().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,h.gt0)(l)){A().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!L(r,u)){A().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,h.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(A().info("killOldProcs(): killing",{reason:d,json:r}),a.push(N(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,D.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,h.gt0)(r))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;return(0,s.pidExists)(r)?(i&&this.recentPids.delete(n),this.recentPids.getOrSet(n,(async()=>{const i=this.pidsDir.join(e.pid+".json"),r=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),s=t.getTime(),n={...e,cmd:r,startTime:s};return await i.writeJson_(n),A().debug("addPid() wrote "+i,n),i}))):(this.recentPids.delete(n),void A().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{A().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(k.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,T.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),S.EndableRanks.predb)}))},86725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(70612)),n=i(84253);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(9678),s=i(7162),n=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),b=i(46852),S=i(69317),P=i(9288),M=i(51053),_=i(71663),T=(0,n.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>E(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function k(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return L();const e=await _.PowerShell.instance().executeJsonToA([x,C].join(" "));return null==e?L():k(e)}():async function(){return R(await(0,S.stdout_)("ps",["-ewwwo","pid,lstart,command"],A))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,b.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,b.thenMap)((0,y.existingPids)(e),(t=>{const i=[s.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const x="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).join(",")}async function I(e){if(_.PowerShell.instance().ended)return L(e);const t=[x,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>k(e)))}const A={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},O=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),s.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",O.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,A),r=(0,d.onlyReqValued)((0,p.parseFixed)(O,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===s.default.pid))||r.push({pid:s.default.pid,start:new Date(v.StartTs),cmd:"node "+s.default.title}),r}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...A,ignoreExitCode:!0})).result)}t.psWinWmic=L},77296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(6231),s=i(3331);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},99869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(43947),s=i(6314),n=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...s)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=s,(0,r.delay)(1).then((()=>e))}return async function(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return s.promise}(...s)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(61570),s=i(82798);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),b=i(71663),S=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(97742)),n=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p()))},8177:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(39784);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(7127),s=i(4657),n=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,s.setupLogger)(),(0,n.logStartup)())}},91710:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const r=i(7383);t.shim0=function({impl:e,name:t}){let i;const s=()=>(0,r.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return s.setShim=e=>{i=e},s.hasShim=()=>null!=i,s}},13378:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const r=i(87748),s=i(44726),n=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,s.isString)(e)?e:(0,r.stringify)(e))}){let o;const l=async i=>{const r=Date.now(),s=await(null!=o?o(i):t(i));return(0,n.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-r),s},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(88491);t.ShortCommandTimeoutMs=7*r.secondMs},55413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const r=t+Math.floor((i-t)/2),s=this.valueOf(this.store[r]);if(e===s)return{found:!0,index:r};e>s?t=r+1:i=r-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,r.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(97742),s=i(58623),n=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(97742),s=i(18991);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},38307:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(97742)),n=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" โ€ฆ(+"+s+" chars)โ€ฆ"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,D=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},63774:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(82798);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(6005)),n=i(24588),a=i(6231);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},97461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(87748),s=i(2023);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},3917:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},31329:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},16417:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},22568:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},3867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(88491),s=i(66776),n=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(4866),s=i(66776),n=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),b=i(19209),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(92332)),n=i(75556);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),b=i(43383),S=i(16475),P=i(66776),M=i(75556),_=i(61570),T=i(26588),E=i(46234),D=i(21669),k=i(7162),x=i(49379),C=i(49273),F="TIMEOUT",I=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new s(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const r=i[e];if(r.name===F)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield r}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,s=A,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},36079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(84253);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}},r=new WeakMap,s=new WeakMap},4691:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(19658);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=r.isTest?e:e||s}},2126:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(97742)),n=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5685:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(89253),a=i(82798),o=i(59387),l=i(70259);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new l.Promises(e,t)}vacuum(){s(this,r,"f").filterInPlace(((e,t)=>!t.signal.aborted))}enqueue(e,t){for(const t of s(this,r,"f").get(e)??[])t.abort();this.vacuum();const i=new AbortController;return s(this,r,"f").add(e,i),this.p.serial((0,a.toS)(e),(()=>t(i)))}},r=new WeakMap},64975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new v(e,t,i,r)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,r,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,n,0,"f"),h(this,s,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,r,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,r,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,n,"f")}isStale(){return null==d(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,s,"f")?void 0:Date.now()-d(this,s,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=async function(e,t){var i;const r=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===r&&h(this,a,i,"f"),d(this,o,"f")?.id===r&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,n,(i=d(this,n,"f"),++i),"f")}},c=function(e){h(this,s,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,r,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(87748),s=i(31737);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const r=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let s,n=!1,a=!1;const o=()=>n?(a=!0,!0===i?void 0:s):(n=!0,s=(0,r.postrun)({fn:e,postrun:()=>{n=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>n,o.prior=()=>s,o.force=async()=>(await s,o()),o}},29106:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(11944),s=i(59694),n=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),b=i(70259);var S=i(26588);async function P(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,u.gt0)(s)?(0,d.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const l=a??(o.length<=s?b.PermissivePromises:new b.Promises(i,(()=>s))),c=(0,u.gt0)(n)?e=>(0,d.thenOrTimeoutError)(t(e),n):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(s);r.push(...await P(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){s=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),b=i(46027);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),b=i(60346),S=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const r=i(41135),s=i(43947),n=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,n.gt0)(t)){const t=await(0,r.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,r.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,s.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38625),s=i(88491),n=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},10347:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(97742)),n=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),b=i(43414),S=(0,n.lazy)((()=>new Set((0,o.values)(b.Settings).map((e=>e.key)))));t.psenv=function(){const e=S();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,n.lazy)((()=>{try{return new RegExp(b.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(b.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,b.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],T=(0,n.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,b.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,b.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,n.lazy)((()=>{const e=P();return(0,y.mapEntries)(s.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:k({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let D=!1;function k({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...T(),...i?(0,f.childProcLocale)():{},...E(r),...e??{}});for(const e of(0,b.transientSettings)())e.deleteFromEnv(s);if((0,m.isLogged)("debug")&&!D){D=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(s),[i,r]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,b.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(r))}return s}t.childEnv=k},69317:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(17718)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),b=i(92661),S=i(4437),P=i(14889),M=i(34996),_=i(46027),T=i(49379),E=i(79141),D=i(83837),k=i(95976),x=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,D.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,b.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{b.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,b.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function A(e,i,r,s=0){const a=new Date,o=[];return(0,S.niceable)(i,r)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,S.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),s-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,b.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,k.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),A(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,D.endStream)(a.stdin);const b=new d.Latch;null==a.stdout?b.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>b.resolve())));const S=new d.Latch;null==a.stderr||s?S.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>S.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:b.state(),stderr:S.state()}),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!r&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const k=i.isIgnorableError??T.isIgnorableError,x=v.filter((e=>!0!==k(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=I,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),A(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},95237:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(6005),u=o(i(97742)),c=i(4866),d=i(11944),h=i(39938),f=i(77125),m=i(61570),p=i(17078),g=i(39784),y=i(50530),v=i(82798),w=i(79378),b=i(7162),S=i(91464),P=i(36079),M=i(91641),_=i(49379),T=i(98462),E=i(90524),D=i(94845),k=i(51053),x=i(69317),C=i(24905),F=i(52289),I=i(95298),A=(0,c.lazy)((()=>(0,b.mkLogger)("child.ChildService")));async function O(e){const t=(0,S.ensureSuffix)(e,".js"),i=T.BaseFile.projectRoot(),r=T.BaseFile.for(u.default.cwd()),s=(0,D.isPacked)()?[i.join("bin",t),k.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];s.push(r.join("dist","app",t));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,D.isPacked)()?p.KB:128))return A().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:D.isPacked,paths:s.map(v.toS)}});return A().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=O,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=["web","sync"];class L{static async mk_(e,t={}){const i=t.pathToService??await O(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,g.toA)(t.nodeArgs),new L(e,i,t)}constructor(e,t,i){r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,F.serviceExitTimeoutMs)(e),this.logger=(0,b.mkLogger)(this.name);const o=[...(0,g.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&o.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale"),this.spawnOpts.forceCLocale=!1,this.wc=new I.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&null!=this.opts.onPreRestart&&await this.opts.onPreRestart(),this.restartCount++,(0,x.spawn)(u.default.execPath,o,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,_.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:C.ChildServiceExitCommand,...i}),(0,P.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(E.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(C.ChildServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,S.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,y.toErr)(i)),this.write(e,t-1)}}}t.ChildService=L,r=new WeakSet,s=function(e){const t=(0,w.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,w.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){if(this.logger.debug(".onStdout(): health check summary",t),"failed"===t.state||"error"===t.level){const e=!0;this.wc.onError(this.name+".onStdout()",t,e)}}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},24905:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},52289:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(55568),s=i(43414),n=i(14889);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},95298:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),b=i(91641),S=i(4691),P=i(70259),M=i(53525),_=i(17875),T=i(79141),E=i(45512),D=i(7162),k=i(75405),x=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,r,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const r=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(r))return a.join("$library",i.posixPathFrom(r));const s=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=s?a.join("$library",i.posixPathFrom(s)):t.baseWithGrandparent},t.stableBasename=h},37980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(7304),s=i(97742),n=i(42041),a=i(39938),o=i(66776),l=i(54883),u=i(19658),c=i(25516),d=i(51081),h=i(51053),f=i(79682),m=i(3142),p=i(29993),g=i(38507);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,this.plugins=[],(0,c.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return this.plugins.push(...e),this}async parse(){let e=(0,f.addFooter)(r.program.description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,a.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n")));(0,o.map)(this.args,(t=>{e=e.arguments(t)}));for(const t of this.plugins)e=t.beforeParse(e);e.option("-V, --version","Output version information (spoiler: it's "+(u.isTest?"1.2.3-test":n.version)+")"),e.on("option:version",(()=>{console.log((0,d.joinLines)(...(0,m.cliWrap)((0,l.EditionName)()+" v"+n.version+"\n"+p.DescriptionFooter))),(0,s.exit)(0)})),e.parse(s.argv,{from:h.isMainElectron?"electron":"node"});const t=e.opts();for(const e of this.plugins)await(e.afterParse?.(t));return e}}},79682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const r=i(51081),s=i(3142),n=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,r.joinLines)(...(0,s.cliWrap)(n.DescriptionFooter)))}))}},3142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const r=i(97742),s=i(75556),n=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},64063:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(43414),s=i(66776),n=i(20902);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors (this overrides NO_COLOR, if set)").option("--no-color","Disable ASCII terminal colors (see https://no-color.org/)"),afterParse:e=>{(0,n.isEnvTrue)("NO_COLOR")&&(r.Settings.logColor.envValue=!1),(0,s.map)(e.color,(e=>r.Settings.logColor.envValue=e))}}},29993:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},85297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(97742)),n=i(39938),a=i(38625);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},9972:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(43414),s=i(38625);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},38507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(4866),s=i(11944),n=i(66776),a=i(75556),o=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},37445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(43414),s=i(82041),n=i(39938),a=i(38625),o=i(4586);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},75862:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(4866),s=i(11944),n=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function I(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function A(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return A(I(e))},t.hsv2hsl=F,t.hsl2hsv=I,t.hsv2rgb=A,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(75556),s=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let M=y*v==0?0:b-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*v)*Math.sin(M/2),T=(i+c)/2,E=(y+v)/2;let D;y*v==0?D=w+b:(D=(w+b)/2,D-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*k/(0,s.sqrt)(20+k),F=1+.045*E,I=1+.015*E*x,A=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*A)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*I),2)+L*P/(a*F)*_/(o*I))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(11944),s=i(75556),n=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},30072:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(13779),o=i(43649),l=i(6667),u=i(6451);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},17566:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),b=i(65976),S=i(53682),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const I=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),A=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:I,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(A),pixelCount:f.length}),{dominantColors:A,description:I,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},64932:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(75556),s=i(61570),n=i(84253);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(75556),s=i(65113),n=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(42748),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(889),s=i(4866),n=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),b=i(50140),S=i(82701),P=i(60299),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(75556),s=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(39938),s=i(75556),n=i(51498),a=i(77696),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(42748),s=i(11944),n=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},55170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},93125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(42748),s=i(39938),n=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=r.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*n.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function b(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=b,t.fmtDateShort=function(e,t="en-US"){return b(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=r.DateTime.DATETIME_MED){return(0,c.opt)(r.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},57510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(65113);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},45161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const r=i(889),s=i(42748),n=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),b=i(50140),S=i(82701),P=i(68074),M=i(54809),_=i(64455),T=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class D{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return s.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new D(t.year,t.month,t.day)}}function k(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,b.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(r=>(0,u.map)((0,w.getMonth)(e),(s=>(0,u.map)((0,w.getDay)(e),(n=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=D,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,c.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${E(n)}:${E(a)}`},t.toExifDateTime=k,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,S.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,b.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):k(e,(0,T.getZoneName)(e))?.toISOString({includeOffset:t})};const x="yyyy:MM:dd HH:mm:ss.SSS",C=x+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function I(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new D(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function A(e,t){const[i,r]=[e,t].map(g.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?s.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,T.hasZone)(t)?C:x):void 0},t.datedToYMD=F,t.toFuzzyDate=I,t.sameDay=function(e,t){return(0,c.lte)(A(e,t),l.dayMs)},t.diffMillis=A,t.closeTo=function(e,t,i){return(0,u.mapOr)(A(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[n,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-n)/(r+1),l=(0,T.getZoneName)(e),u=l===(0,T.getZoneName)(t)?l:void 0,c=s.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some((e=>!(0,b.hasTime)(e)))?I(c):c},t.setZone=function(e,t,i){const r={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,T.hasZone)(e)},s=(0,M.normalizeZone)(t);if(null!=e&&null!=s&&(0,b.hasTime)(e))return e instanceof m.DateInterval?e.setZone(s,r):k(e)?.setZone(s,r)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const r=(0,T.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),b=i(43414),S=i(44665),P=i(76387),M=i(85590),_=i(55170),T=i(45161),E=i(50140),D=i(82701),k=i(92166),x=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=A({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function A({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const t of n){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,x.isValidDate)(i))return i}}t.parseDated=A;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=A({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,k.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(66776),s=i(75556),n=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},50140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(889),s=i(75556),n=i(61570);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},82701:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(42748);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(42748),s=i(4866),n=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(4866),s=i(59694),n=i(75556),a=i(36218),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},44731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(42748),s=i(4866),n=i(92507),a=i(43414);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},54809:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const I=/\b(?(?:Etc\/)?GMT)\b/,A=(0,n.lazy)((()=>(0,m.concatRegexp)([I,T,k,m.RegExpOptional.from(x)])));function O(e){return F(A().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),b=i(68074),S=(0,n.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,n.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,b.datedToLocal)(e)))))),T=(0,n.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=k(e);return S().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const D=String(new Date("bad"));function k(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===D)return D;if(e instanceof r.ExifDateTime||e instanceof g.DateInterval||e instanceof s.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof r.ExifDate){if(!L(e.year,e.month,e.day))return"not valid YMD"}else{const t=s.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return T().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,b.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return S().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=k,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const x=(0,n.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,n.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function I(e){return(0,h.within)(x(),C(),e)}function A(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function O(e,t,i){return(0,u.gt0)(i)&&s.DateTime.fromObject({year:e,month:t,day:i}).isValid}function L(e,t,i){return I(e)&&(!(0,u.gt0)(t)||A(t,e))&&(!(0,u.gt0)(i)||O(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>x.unset())),(0,m.ee)().on("clearCache",(()=>{x.unset(),C.unset(),F.unset()}))})),t.validYear=I,t.validMonth=A,t.validDay=O,t.validYMD=L},60299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(889),s=i(75556),n=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(84253);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},9452:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(44726),s=i(1629),n=i(53525),a=i(98250),o=i(43586),l=i(47987),u=i(43414),c=i(62936);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},24193:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(4866),s=i(82341),n=i(7162),a=i(43414),o=i(9452),l=i(62936),u=i(76915),c=i(92345),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},29393:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(84253);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},21808:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(4866),s=i(7162),n=i(61253),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},3293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(7162),s=i(49379),n=i(43414),a=i(43383),o=i(43947),l=i(23175),u=i(7383),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i){const r=Date.now();let a=0;const d=r+n.Settings.maxBusyDbMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=d)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const r=(0,l.randomInt)(500,1500)*++a;c().warn(e+": Caught db error. Retrying in "+r+"ms.",{name:e,error:t}),i?.(),await(0,o.delay)(r)}}return c().throw(e+": handleDbRetries(): timeout after "+n.Settings.maxBusyDbMs.valueOrDefault+"ms")}))}},80807:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(76387),s=i(85590),n=i(11944),a=i(61570);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},66097:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(4866),s=i(19658),n=i(43414);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*(s.isTest?.25:5))))},5853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(49411),s=i(75556),n=i(17078),a=i(82798),o=i(7162),l=i(55568),u=i(37086),c=i(3955),d=i(35008),h=i(63410),f=i(95976),m=i(43414),p=i(59387),g=i(85890);function y(){const e=m.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,s.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=m.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=m.Settings.logSql.valueOrDefault}){let s;e=(0,d.resolve)(e),(0,c.mkdirpSync_)((0,r.dirname)(e));const v=(0,c.posixPathFromGrandparent)(e);if(i){const e=(0,o.mkLogger)("SQLite("+v+")"),t=(0,f.defaultLogLevel)();s=i=>e.log(t,i.replace(/\s{2,}/g," "))}const w=(0,h.nativePathSizeSync)(e),b=(0,o.mkLogger)("db.mkdb("+v+")");if(null!=w){const t=Math.round(w/n.MiB),i=Math.ceil(1.5*t);i>m.Settings.dbCacheSizeMb.valueOrDefault&&(b.info("Dynamically setting dbCacheSize to "+m.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:t}),m.Settings.dbCacheSizeMb.envValue=i);const r=Math.round(1.5*t);r>m.Settings.maxMemoryMb.valueOrDefault&&(b.warn("Large database: setting maxMemoryDb to "+r+"MB",{dbFileSizeMb:t,"Settings.maxMemoryMb":m.Settings.maxMemoryMb.valueOrDefault}),m.Settings.maxMemoryMb.envValue=r)}b.info("Opening "+e+"...");const S=new g(e,{fileMustExist:!1,readonly:!1,timeout:t,verbose:s});b.info("Open. Setting PRAGMAs...");for(const e of['encoding = "UTF-8"',"threads = "+(0,p.maxCpus)(),"foreign_keys = ON","page_size = "+y(),"trusted_schema = 0","cache_size = -"+Math.round(m.Settings.dbCacheSizeMb.valueOrDefault*n.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","busy_timeout = "+m.Settings.dbBusyTimeoutMs.valueOrDefault,"synchronous = "+m.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,l.isDbJanitorService)()?(0,a.toS)(m.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+m.Settings.dbAutoVacuumMode.valueOrDefault])b.tapThunk({msg:"PRAGMA "+e,result:()=>S.pragma(e)});const P=S;return P.__uid=(0,u.uid)(),P},t.pageSizeBytes=y},94794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(84253);t.RepairModes=(0,r.strEnum)("dump","recover")},11978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(11944),s=i(75556),n=i(39784),a=i(66097),o=i(76851);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},61253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(95725),s=i(65886),n=i(76915);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},76851:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(11944),s=i(75556),n=i(82798),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+\n/g,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(4866),s=i(24603),n=i(23175),a=i(7162),o=i(98250),l=i(5853),u=i(61253),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},65886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},34879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(20681),s=i(69317),n=i(22143),a=i(53719),o=i(85890);t.sqliteVersion_=(0,r.lazyAsync)({later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},62936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(84253),s=i(76915);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models","stats"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(84253);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),b=i(15203),S=i(51053),P=i(43414),M=i(95699),_=i(58676),T=i(51510),E=i(10156),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=S.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function x(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:_.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(S.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:S.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=S.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=x,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:x(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(4866),s=i(15203),n=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},29223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(14889),o=i(69317),l=i(76531),u=i(9483),c=i(51053),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},58676:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(63410),s=i(15203),n=i(58676);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(49411)),n=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(39938),s=i(20902),n=i(3955);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44470),s=i(11944),n=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(70612),s=i(49411),n=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,n.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},85943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(3955),s=i(1629),n=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},96416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(4866),s=i(39938),n=i(87748),a=i(17078),o=i(7162),l=i(62936),u=i(10408),c=i(95725),d=i(76531),h=i(82041),f=i(82341),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},14195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(39938),s=i(82798),n=i(3955),a=i(43414);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(11944),s=i(66776),n=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e))}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},35796:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38625),s=i(19658),n=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!s.isProd&&!(0,n.isPacked)()&&(0,r.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38625),s=i(29405);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},29405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(87561)),n=i(49411),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,h.debom)(s.default.readFileSync(r)),n=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,d.entries)(n))t.test(e)||(i[e]=r)}catch(e){console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(84253);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(39938),s=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(97742)),n=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(5712),s=i(4866),n=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},82987:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(11944),s=i(16475),n=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(11944),s=i(59694),n=i(84253),a=i(1058);t.ErrorFlags=(0,n.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},27519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(4866),s=i(88491),n=i(19067),a=i(66776),o=i(75556),l=i(61570),u=i(39784),c=i(82798),d=i(7162),h=i(14889),f=i(29731),m=i(4691),p=i(4586),g=i(53525),y=i(25015),v=i(3955),w=i(98250),b=i(6231),S=i(43414),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},49379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(11944),s=i(38625),n=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,s.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const b=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!b.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(53525);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},17875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(39938),s=i(75556),n=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const r=i(4866),s=i(87489);function n(e,...t){return s.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=n,t.broadcastPause=function(){return n("pause")},t.broadcastResume=function(){return n("resume")},t.broadcastExit=(0,r.lazy)((()=>n("exit")))},80313:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],r.set(this,new Map),s.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(n(this,r,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},82166:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const r=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,r.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const r=i(71239),s=i(4866),n=i(80313);function a(e){const t=new r.EventEmitter;return t.setMaxListeners(70),new n.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,s.lazy)(a)},95856:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const r=i(79015);let s=!1;t.isSyncing=function(){return s},t.setIsSyncing=function(e){s!==e&&(s=e,(0,r.ee)().emit("syncing",e))}},2614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const r=i(39938),s=i(61570),n=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,n.strEnum)(...(0,s.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,n.strEnum)(...(0,s.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,r.notBlank)(e.result)||(0,r.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),b=i(92332),S=i(4866),P=i(11944),M=i(59694),_=i(38625),T=i(88491),E=i(43383),D=i(24603),k=i(16475),x=i(1429),C=i(87748),F=i(21040),I=i(66776),A=i(75556),O=i(61570),L=i(20636),R=i(39784),N=i(7162),B=i(70283),j=i(55568),z=i(14889),V=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Y=i(21142),X=i(80294),Z=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),re=i(95694),se=i(95741),ne=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,S.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,re.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),r=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return r&&"exit"===e.name?(0,A.gt)(i,V.StartTs):r}function be(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,A.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=T.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=be;class Se extends J.EndableWrapper{constructor(e,i=String(w.pid),s=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,r,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),r.add(this),this.dir=e,this.id=i,this.eventEmitter=s,this.processors=l,n.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,S.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,j.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,r,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,n,(0,b.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),T.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),r=(0,C.parseJSON)(e);null!=r&&i.push(r)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let s=!1;if((0,P.isEmpty)(i))return;const n=be((0,x.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:n});for(const e of n)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),s||(s=p(this,r,"m",f).call(this,e));s&&await this.save();const a=(0,x.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,A.gt)((0,q.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,r,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,r,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,j.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,D.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,O.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},s=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?s.observe(p(this,r,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(s.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"uncaught rejection: "+(0,Z.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,s),this.save(),s)}}t.SharedState=Se,s=Se,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,S.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*T.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:z.ShortCommandTimeoutMs,intervalMs:T.secondMs}),p(this,o,"f").destroy(),(0,I.map)(p(this,n,"f"),b.clearInterval),g(this,n,void 0,"f")},h=function(e){if(!(0,j.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:s}){const n=this.processors.filter((e=>e.accept(t)));if(0===n.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(s)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,r,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;n.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:n.map((e=>e.name))});for(const e of n)try{a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,result:await(0,L.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-"+e.name,error:(0,Z.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,j.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(s,s,"f",u)),ce.Settings.cacheDir.watchLater(p(s,s,"f",u)),ce.Settings.sharedStateDir.watchLater(p(s,s,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,se.nativePathsEqlSync)(e,s.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(s.instance()),s.instance.refresh())}},Se.instance=(0,S.lazy)((()=>{if((0,j.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,k.shortStack)());p(s,s,"f",l).call(s);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new s(ne.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return Se.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=Se.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>ne.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const r=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){r.isTest&&(t.taskProcessors.length=0)}},9816:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateReadyToInstall=void 0;const r=i(43947),s=i(79015);let n=!1;(0,r.later)((()=>(0,s.ee)().on("updateReadyToInstall",(()=>n=!0)))),t.isUpdateReadyToInstall=function(){return n}},28941:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiHealthRouter=void 0;const s=r(i(66860)),n=i(43383),a=i(79403),o=i(77368);t.ApiHealthRouter=class{constructor(e="/api/health"){this.mountpoint=e,this.router=(0,n.defer)((()=>s.default.Router().get(this.mountpoint,(0,o.wrap)(this.constructor.name+".health",this.health)))),this.health=async(e,t)=>{t.json(await a.HealthCheck.awaitSettled())}}}},77368:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableCache=t.truthyQuery=t.extractLang=t.requestLang=t.extractTagPath=t.jsonOrRedirect=t.getSeedOrRedirect=t.getFit=t.getSeed=t.wrap=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(98510),u=i(33912),c=i(31869),d=i(86768),h=i(82798),f=i(13779),m=i(7162),p=i(70283),g=i(7383),y=i(53525),v=i(79141),w=i(36297),b=i(22189),S=i(50080),P=(0,r.lazy)((()=>(0,m.mkLogger)("express.Handlers")));function M(e){return(0,l.opt)(e).filter(n.notBlank).map(h.toS).map((e=>e.split(","))).map(s.compactBlanks).map((e=>e.map((e=>e.split(";").map((e=>e.trim())))))).flatMap((e=>(0,f.greatestBy)(e,(([,e])=>(0,p.firstGt0)((0,p.extractFloat)(e),1))))).map((([e])=>e)).get()}t.wrap=function(e,t){return async(i,r,s)=>(0,g.time)(e,(()=>(0,S.wrapWithToast)({f:()=>t(i,r,s),response:r})))},t.getSeed=function(e){return(0,u.toSeed)(e.query.seed)},t.getFit=function(e){return c.ThumbFits.validOrElse((0,h.toS)(e.query.fit),c.ThumbFits.square)},t.getSeedOrRedirect=function(e,t){const i=(0,u.toSeed)(e.query.seed);if(null==i){let i=(0,b.requestedUri)(e);"/tag/"===i.path&&(i=i.with({path:"/tag"})),i.query.append("seed",(0,h.toS)((0,u.prngSeed)())),t.redirect(i.toString())}return i},t.jsonOrRedirect=function(e,t){if(null==e)return(0,S.sendErrorToast)(new v.WrappedError("Internal error: jsonOrRedirect(null)"+y.InternalErrorFlag,{fatal:!1,doNotSend:!0}),t,404);for(const i of[d.XLocationRedirect,d.XLocationReplace]){const r=e[i];(0,n.notBlank)(r)&&(P().debug("jsonOrRedirect(): "+i,r),t.setHeader(i,r),t.status(w.HttpStatus.SeeOther))}return t.json(e)},t.extractTagPath=function(e){const t=e.replace(/^(?:\/api)?\/tag\/?/,""),i=t.split("/").map(decodeURIComponent),r=(0,n.blank)(t)?[]:i;return P().info("extractTagPath()",{path:e,result:r,trimmed:t,tagPath:i}),r},t.requestLang=function(e){const t=e.headers["accept-language"];return M(Array.isArray(t)?t.join(","):t)},t.extractLang=M,t.truthyQuery=function(e,t){return(0,o.mapOr)(e.query[t],(e=>!(0,a.isFalse)(e)),(()=>!1))},t.disableCache=function(e){e.setHeader("Cache-Control","no-store, max-age=0"),e.setHeader("Pragma","no-cache"),e.setHeader("Expires","Fri, 01 Jan 1990 00:00:00 GMT")}},47058:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onFinished=void 0,t.onFinished=function(e,t){let i=!1;e.on("error",(r=>{i||(i=!0,t(r,e))}));const r=()=>{i||(i=!0,t(null,e))};for(const t of["end","finish","close"])e.on(t,r);return e}},53235:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectRouter=void 0;const s=r(i(66860)),n=i(83769),a=i(36297),o=i(50080);t.redirectRouter=function(e){return s.default.Router().use(((t,i)=>(0,n.isAjaxRequest)(t.headers)?(0,o.sendRedirectionToast)({response:i,redirectOrReplace:"redirect",url:"/splash"}):i.redirect(a.HttpStatus.Found,e)))}},68079:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.referrer=t.isXhr=void 0;const r=i(82798),s=/^XMLHttpRequest$/i;t.isXhr=function(e){return e.xhr||null!=s.exec((0,r.toS)(e.header("X-Requested-With")))},t.referrer=function(e){return e.header("Referer")}},77659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequestLogger=void 0;const r=i(66860),s=i(4866),n=i(39938),a=i(88491),o=i(66776),l=i(7162),u=i(17875),c=i(79403),d=i(7258),h=i(81026),f=i(60346),m=i(43414),p=i(36297),g=i(47058),y=i(22189);t.RequestLogger=class{constructor(){this.logger=(0,l.mkLogger)("web.RequestLogger"),this.responseTimes=new f.Average,this.accessLogger=m.Settings.logWebRequests.valueOrDefault?new h.LogWriter((0,n.firstNotBlank)(m.Settings.logWebDir.valueOrDefault,m.Settings.logDir.valueOrDefault),{processName:(0,s.lazy)((()=>"webrequest"))}):void 0,this.router=(0,r.Router)().use(((e,t,i)=>{const r=Date.now(),s=e.method,n=`${e.protocol?.toUpperCase()}/${e.httpVersion}`,l=`${s} ${(0,y.requestedUri)(e)} ${n}`,h="/updates"===e.path||"/api/splash"===e.path||"/api/status"===e.path?void 0:setTimeout((()=>this.logger.warn("Request is still processing: "+l,{elapsedMs:Date.now()-r})),4*(this.responseTimes.p84??a.secondMs));(0,g.onFinished)(t,(i=>{(0,o.map)(h,clearTimeout),null!=i&&(0,u.onError)(l,{error:i});const a=p.HttpStatusIs.success(t.statusCode)||p.HttpStatusIs.redirect(t.statusCode),f=Date.now()-r,m={from_ip:e.ip,protocol:n,method:s,statusCode:t.statusCode,ok:a,elapsedMs:f,runState:c.HealthCheck.runState(),userAgent:e.headers["user-agent"]};null!=i&&(m.error=i),this.responseTimes.push(f),(0,d.logBroadcaster)()?.log(a?"info":"warn","HttpRequestLogger",l,m),this.accessLogger?.log("info","",l,m),null==d.logBroadcaster.prior()&&null==this.accessLogger&&this.logger.log(null==i&&a?"debug":"warn",l,m)})),i()}))}}},22189:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addXSettingsHandler=t.requestedUri=void 0;const r=i(4866),s=i(43947),n=i(87748),a=i(42041),o=i(68074),l=i(79015),u=i(69060),c=i(43414),d=i(19209),h=i(67220),f=(0,r.lazy)((()=>({protocol:"http",host:c.Settings.hostname.valueOrDefault??"localhost",url:"/"})));t.requestedUri=function(e,t){const i={...f(),...t};return d.URI.parse((e?.protocol??i.protocol)+"://"+(e?.headers?.host??i.host)+(e?.originalUrl??i.url))};const m=(0,r.lazy)((()=>"lite"));async function p(){m.set(await(0,u.t)()),y.unset()}const g=(0,r.lazy)((()=>(0,c.isProd)()?"":"+"+(0,o.nowLocal)())),y=(0,r.lazy)((()=>{const e={ver:a.version+g(),paused:(0,h.isPaused)(),ll_vh:c.Settings.lazyLoadExtraVh.valueOrDefault,tier:m()};return Buffer.from((0,n.stringify)(e)).toString("base64")}));(0,s.later)((()=>{(0,l.ee)().on("settingsChanged",(()=>y.unset())),(0,l.ee)().on("reloadLicenses",p),u.m.watch(p),(0,l.ee)().on("pause",(()=>y.unset())),(0,l.ee)().on("resume",(()=>y.unset()))})),t.addXSettingsHandler=function(e,t,i){t.setHeader("X-Settings",y()),i()}},9786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serveStaticGz=void 0;const r=i(39938),s=i(82798),n=i(7162),a=i(48783),o=i(91464),l=i(53525),u=i(98462),c=i(63526),d=i(77368),h=/\.asar\/?/i;t.serveStaticGz=async function(e){const t=(0,n.mkLogger)("serveStaticGz"),i=u.BaseFile.for(e),f=await i.descendants((e=>e.ext.endsWith(".gz"))),m=(0,a.toMap)(f,(e=>(0,r.mapNotBlank)((0,c.extMimetype)((0,o.stripSuffix)(e.ext,".gz")),(t=>["/"+(0,o.stripSuffix)(e.posixPathFrom(i),".gz"),{contentType:t,nativePath:e.nativePath}]))));return t.debug("ready to serve",[...m.keys()]),0===m.size&&t.error("Can't read "+i+". Please visit https://forum.photostructure.com/ for help."+l.FatalErrorFlag),(0,d.wrap)("serveStaticGz",(async(e,i,r)=>{if(null!=e.path.match(h))return i.sendStatus(404);const n=m.get((0,s.toS)(e.path));return null==n?r():(t.debug("get",{path:e.path,result:n}),i.set("Content-Encoding","gzip"),i.set("Content-Type",n.contentType),i.sendFile(n.nativePath))}))}},41749:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSentEventsRouter=void 0;const s=r(i(66860)),n=i(11944),a=i(39938),o=i(91641),l=i(95557),u=i(83837),c=i(232),d=i(77368);class h extends l.EndableWrapper{constructor(e){super("SSERouter("+e+")",(()=>this.close()),o.EndableRanks.first),this.path=e,this.streams=[]}router(){return s.default.Router().get(this.path,(0,d.wrap)(this.name,this.updates.bind(this)))}close(){this.streams.map(u.endStream),this.streams.length=0}async updates(e,t){if(this.ended)return void t.sendStatus(503);this.logger.info("Sending updates to "+(e.ip??e.ips));const i=(0,u.remoteDesc)(e.socket);t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),this.streams.push(t),t.once("error",(e=>{(0,n.removeSame)(this.streams,t),this.logger.warn("onError("+i+")",{error:e})})),t.once("close",(()=>{(0,n.removeSame)(this.streams,t),this.logger.debug("stream to "+i+" closed. ("+this.streams.length+" remain)")}));const r=(0,n.compact)(this.firstEvents(e,t));(0,n.isNotEmpty)(r)&&(this.logger.info("firstEvents",{firstEvents:r}),t.write((0,c.mkEventStream)(...r)))}endStream(e){(0,u.endStream)(e),(0,n.removeSame)(this.streams,e)}writeToStreams(...e){const t=(0,c.mkEventStream)(...e);if(this.logger.info("writeToStreams",{events:e,payload:t}),!(0,a.blank)(t))for(const e of this.streams)if(!0===e?.closed||null==e?.socket)this.endStream(e);else try{e.write(t)}catch(t){null==e.socket||e.closed?this.endStream(e):this.logger.warn("writeToStreams failed to write to stream",{stream:(0,u.remoteDesc)(e.socket),error:t})}}}t.ServerSentEventsRouter=h},50080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapWithToast=t.expressErrorHandlerWithToast=t.sendErrorToast=t.send404Toast=t.sendWarningServerToast=t.sendRedirectionToast=t.sendServerToast=t.requireEnabled=t.requirePlus=void 0;const r=i(4866),s=i(66776),n=i(86768),a=i(23418),o=i(48652),l=i(50530),u=i(7162),c=i(10408),d=i(49379),h=i(69060),f=i(83769),m=i(36297),p=i(22189),g=(0,r.lazy)((()=>(0,u.mkLogger)("express.ServerToastHelpers")));function y({response:e,toast:t,httpStatusCode:i,reload:r}){return(0,s.map)(i,(t=>e.status(t))),g().warn("sendServerToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,httpStatusCode:i}),e.json({toast:t,reload:r})}function v(e,t,i){g().warn("sendErrorToast",e);const r=(0,d.stripErrorFlags)((0,c.errorToS)(e));y({response:t,toast:{text:404===i?"Not found":"Well, darn, that didn't work",uuid:r,details:r,type:(0,d.isFatalError)(e)?"error":"warning",button1Text:"Return home",button1Url:"/"+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor},httpStatusCode:i??m.HttpStatus.ServiceUnavailable})}t.requirePlus=async function(e,t,i){if(await(0,h.l)()){const e={toastPlusOnly:!0};return t.status(m.HttpStatus.Forbidden),t.json(e)}return i()},t.requireEnabled=function(e){return(t,i,r)=>e.valueOrDefault?r():y({response:i,toast:{text:"This has been disabled by your administrator.",details:`(see setting "${e.name}")`,type:"warning"},httpStatusCode:m.HttpStatus.Forbidden})},t.sendServerToast=y,t.sendRedirectionToast=function({response:e,toast:t,url:i,redirectOrReplace:r}){if((0,f.isAjaxRequest)(e.req.headers)){const s="replace"===r?n.XLocationReplace:n.XLocationRedirect;return e.setHeader(s,i),g().warn("sendRedirectionToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,key:s,url:i}),e.json({toast:t})}return e.redirect(i)},t.sendWarningServerToast=function({response:e,toast:t,httpStatusCode:i,reload:r}){return t.type??(t.type="warning"),y({response:e,toast:t,httpStatusCode:i,reload:r})},t.send404Toast=function({text:e,details:t,response:i,httpStatusCode:r=404}){return y({response:i,toast:{text:e,details:t,type:"warning",button1Text:"Go home",button1Url:(0,o.mkHomeFullPath)()+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor,timeout:!1},httpStatusCode:r})},t.sendErrorToast=v,t.expressErrorHandlerWithToast=function(e,t,i,r){null==e?r():v(e,i)},t.wrapWithToast=async function({f:e,response:t}){try{await e()}catch(e){(0,s.map)((0,l.toErr)(e),(e=>v(e,t)))}}},1597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.viewRouter=void 0;const s=r(i(66860)),n=i(77368);t.viewRouter=function({path:e,view:t,modeler:i}){return s.default.Router().get(e,(0,n.wrap)(t+"Router",(async(e,r)=>{const s=await(i?.(e,r))??{};return s.nonce=r.locals?.cspNonce,r.render(t,s)})))}},44982:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(87561)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(r&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},77390:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(49411)),n=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(87561),s=i(49411);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},98462:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),b=f(i(47261)),S=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),T=i(39938),E=i(88491),D=i(24603),k=i(1429),x=i(87748),C=i(66776),F=i(75556),I=i(61570),A=i(98510),O=i(65113),L=i(44726),R=i(39784),N=i(82798),B=i(13779),j=i(34996),z=i(46852),V=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Y=i(91464),X=i(2073),Z=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),re=i(57400),se=i(93033),ne=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof Se};const be=(0,P.lazy)((()=>new ne.FileCache({name:"fs.BaseFile"})));class Se{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((()=>(0,z.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Se?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Se)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const s=(0,he.resolve)(i),n=new Se(s,t);return be().set(i,n),be().set(s,n),n}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Se.for(e,t)}forDirectoryEntry(e){return Se.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Z.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,z.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Se,n=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Se.attrTTL=3*E.minuteMs,Se.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Se.for(e)})),t.execDir=function(){return Se.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(43414),s=i(17310),n=i(63526),a=i(3955);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},51081:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(11944),s=i(1429),n=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},94488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(49411),s=i(4866),n=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,n.AppNameVersion)()}`)}},88462:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(1487),s=i(4866),n=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,s.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const s=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(s);const o=new c.FifoCache(1024),d=await(0,r.subscribe)(s,(async(e,i)=>{g().trace("callback",{nativePath:s,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:s}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,n.isNotEmpty)(i))&&t(e,i)}));return new y(s,d,o,i)}constructor(e,t,i,r){super("fs.DirWatcher("+e+")",(()=>this.close()),r),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,s.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),b=i(76531),S=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(49411)),n=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),b=i(2023),S=i(46852),P=i(4586),M=i(10156),_=i(85943),T=i(82341),E=i(20902),D=i(9483),k=i(51053),x=i(38336),C=i(51776),F=i(43414),I=i(77390),A=i(98462),O=i(64546),L=i(28659),R=i(1391),N=i(69716),B=i(95725),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:A.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ae,notNoMedia:se,notHidden:ne}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,L.hasNoMedia)(e))}function ne(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,I.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},27522:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const u=i(4866),c=i(11944),d=i(88491),h=i(75556),f=i(59390),m=i(7162),p=i(19658),g=i(99869),y=i(28807),v=i(91641),w=i(4691),b=i(77696),S=i(79015),P=i(57400),M=i(28659);class _{static for(e){return new _(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,n,c=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=n,this.minRetained=c,s.set(this,void 0),this.intervalMs=(0,u.lazy)((()=>(0,h.clamp)(p.isTest?0:5*d.minuteMs,d.dayMs,this.staleMs/2))),this.scheduleInterval=(0,u.lazy)((()=>new y.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}))),this.cleanup=(0,g.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>l(this,r,"m",a).call(this)}),o(this,s,(0,m.mkLogger)("fs.FileCleanup("+e+")"),"f")}}t.FileCleanup=_,s=new WeakMap,r=new WeakSet,n=async function(e){if(!(0,h.gt0)(this.minRetained))return new Set;const t=new f.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},a=async function(){try{if((0,w.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await P.DirectoryEntry.for(e);if(null==t)return[];l(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,b.fmtFullDuration)(this.staleMs," ")});const i=await l(this,r,"m",n).call(this,t),a=Date.now()-this.staleMs,o=new Set,u=[],d=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,h.gte)(e.mtimeMs(),a)))if(e.isDirectory())try{await e.rmdir_(),d.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(l(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,S.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&l(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),u.push(e.nativePath),o.add(e.dir)}catch(t){l(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const f=[...u,...d];return(0,c.isNotEmpty)(f)&&t.clear(),l(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:u.length,pruned_dir_count:d.length}),f}catch(e){return void l(this,s,"f").error("cleanup() failed",{error:e})}}},25015:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const r=i(87561),s=i(4866),n=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,n.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,s.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const r=i(93977),s=i(61570),n=i(95725);t.fileStats_=async function(e){return(0,s.pick)(await(0,r.stat)((0,n.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(53221),s=i(4866),n=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},14980:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(66776),s=i(20636),n=i(91464),a=i(29731),o=i(4586),l=i(19653),u=i(98250);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},19653:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},S=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=S(i(44470)),_=i(92332),T=i(11944),E=i(37609),D=i(88491),k=i(24603),x=i(19067),C=i(66776),F=i(75556),I=i(23175),A=i(20636),O=i(82798),L=i(19658),R=i(1058),N=i(55568),B=i(91641),j=i(95557),z=i(4691),V=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,s,Math.max(Date.now(),w(this,s,"f",n)+1),"f",n),(0,T.compactBlanks)([q.TokenRadix.encode(w(this,s,"f",n)),N.serviceName.prior(),(0,O.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,O.toS)(e))?.groups?.pid)}static for(e){return w(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=s,s,(i=w(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(s,s,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,r,"m",f).call(this,e)??w(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,L.isTest?10:D.secondMs);b(this,c,setInterval((()=>w(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,T.filterInPlace)(w(s,s,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),b(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?w(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>w(this,r,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,A.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await w(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!L.isTest)return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(39938),s=i(44726),n=i(82798),a=i(95725);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),b=i(61570),S=i(20636),P=i(12308),M=i(28807),_=i(91641),T=i(17354),E=i(79015),D=i(3955),k=i(8177),x=i(43414),C=i(91464),F=i(37086),I=i(59873),A=i(95725),O=i(76531),L=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,k.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,k.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const r=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,r),r.on("close",(()=>{this.path2watcher.delete(e)})),r.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,D.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,D.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,A.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),r.add(this),this.args=e,this.id=(0,F.uid)(),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,L.statSync)(this.targetNativePath);return u(this,s,null==e?void 0:(0,b.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,r,"m",o).call(this),!0===e?.isFile()&&await c(this,r,"m",l).call(this),this.logger.info("setup()",{stat:c(this,s,"f"),sha:c(this,n,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault),this.check=(0,T.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,s,"f")});const e=c(this,s,"f"),i=await(0,O.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,s,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const n=(0,b.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,n),d=i.isDirectory()?await c(this,r,"m",o).call(this):!a&&!!i.isFile()&&await c(this,r,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:n,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,s,n,"f"),this.args.onChange())}}),this.targetNativePath=(0,A.toNativePath_)(e.target);const i=e.watchDebounceMs??x.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,s,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,s,void 0,"f"),u(this,n,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(){const e=await(0,S.thenOrTimeout)(h.default.readdir(this.targetNativePath),x.Settings.statTimeoutMs.valueOrDefault);if(e===S.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:x.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,n,"f"))&&(u(this,n,e,"f"),!0)}},81666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(39938),s=i(66776),n=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},16958:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(87561)),n=i(84492),a=i(76402),o=i(82798),l=i(94329),u=i(95725),c=i(16414);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},40374:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44470)),n=r(i(87561)),a=i(76402),o=r(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(6005)),n=r(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(4866),s=i(88491),n=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,r.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(39938),s=i(82798),n=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||n.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||n.isTest?/^\/private\//i:void 0,d=a.isMac||n.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||n.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},61861:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(4866),s=i(66776),n=i(79141),a=i(7162);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},94329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(84492),s=i(44726),n=i(82798);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(49411)),n=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(77390),s=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=n(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function b(e){return[e,e.toLowerCase(),e.toUpperCase()]}const S=Object.freeze([...b("."+w),...b(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const r=await Promise.race([T(e,t),D(e,t)]);return t.halt(),r}(t.nativePath)))}async function T(e,t){for(const i of S){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const r of t){if(!0===i?.halted)return null;if(P(r.basename))return y().tap({msg:e+" has a noMedia child, "+r.basename,result:!0});if(r.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,r.basename)))return!0}return!1}async function D(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),b=i(76531),S=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return x(e).some(M)},t.isNotHiddenPosixPath=function(e){return x(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return T((0,y.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return n.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=_.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function E(e){const t=n.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,m.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(g.isLinux?r===s:(0,m.equalsIgnoreCase)(r,s))}function x(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),g.isWin?"":n.default.sep)}t.parseNativePath=T,t.parentBasename=E,t.grandParentBasename=function(e){return E(n.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(w.toNativePath_,e,t)},t.toPathnames=x,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&x(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:x(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,y.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=x(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),F([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("โ€ฆ"),F([...s,...n])},t.posixPathFromParent=function(e){return x(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return x(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;await s.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,S.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,S.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(49411)),n=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),b=i(76531),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),b=i(39938),S=i(88491),P=i(16475),M=i(19067),_=i(66776),T=i(75556),E=i(61570),D=i(20636),k=i(49049),x=i(17078),C=i(82798),F=i(13779),I=i(7162),A=i(14889),O=i(91464),L=i(46852),R=i(7383),N=i(21142),B=i(69317),j=i(14195),z=i(53525),V=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Y=i(19209),X=i(25116),Z=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),re=i(25015),se=i(19653),ne=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:A.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),r=new pe(i,t);return(0,O.isString)(e)&&me().set(e,r),me().set(i,r),r}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,O.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,O.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:A.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(A.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,T.clamp)(A.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),b=i(64067),S=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function I(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function A(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:I}]}function O(e){return[...A(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=I,t.simpleFileFiltersFor=A,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...A(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...A(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...A(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},1391:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(49411)),n=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},27175:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const s=r(i(49411)),n=r(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>s.default.dirname(n.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(s.default.join((0,t.execDir)(),"resources"),s.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const r=s.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44470),s=i(4866),n=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44470),s=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},41544:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44470),s=i(51081);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},96895:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(84492);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},75123:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(93977)),n=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),b=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const S=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){S().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function T(e){return S().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=E(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(s===h.Timeout&&(0,p.onTimeout)({soft:!1}),s!==h.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?T(e):E(e))}catch(t){return void S().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const s=r(i(49411)),n=i(39938),a=i(1963);t.resolve=function(...e){if((0,n.blank)(e.join("")))throw new Error("resolve(): empty paths");return s.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(94383),s=i(43414),n=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},57294:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.showFileInFolder=void 0;const r=i(5712),s=i(17718),n=i(4866),a=i(11944),o=i(7162),l=i(51053),u=i(71663),c=i(43414),d=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ShowFileInFolder")));async function h(e,t){try{(0,s.spawn)(e,t,{detached:!0,stdio:"ignore"}).unref()}catch(i){d().warn("spawn() failed",{err:i,cmd:e,args:t})}}t.showFileInFolder=async function(e){if(await e.isEmpty())return!1;if(c.Settings.showFileInFolderUsesThunar.valueOrDefault&&l.isLinux)return async function(e){return h("dbus-send",["--type=method_call","--dest=org.xfce.Thunar","/org/xfce/FileManager org.xfce.FileManager.DisplayFolderAndSelect",`string:"${e.dir}"`,`string:"${e.base}"`,'string:""','string:""'])}(e);if((0,a.isNotEmpty)(c.Settings.showFileInFolderCommand.values)){const t=c.Settings.showFileInFolderUsesFileUri.valueOrDefault?e.fileuri():e.nativePath,i=[...c.Settings.showFileInFolderCommand.values,t],r=i.shift();return d().info("custom showFileInFolderCommand: running",{cmd:r,args:i}),h(r,i)}return l.isLinux?async function(e){return h("nautilus",["-s",e.fileuri()])}(e):l.isWin?async function(e){const t=e.nativePath.replace(/"/g,"").replace(/'/g,"''");try{return await u.PowerShell.instance().execute(`start explorer.exe -ArgumentList '/select,"${t}"'`,r.SimpleParser),!0}catch(t){return d().warn("explorerSelect("+e+") failed",t),!1}}(e):!!l.isMac&&async function(e){return h("open",["-R",e.nativePath])}(e)}},13594:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(39938),s=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},95725:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const s=r(i(87561)),n=r(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function b(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" โ‰  "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(P(r),P(s));if(null==n||n>1)return"unmatched "+i+": "+r+" โ‰  "+s}}t.stat_=w,t.statMaybe=b,t.statToType=S,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await b(e,t)},t.isEmptyFile=async function(e,t){const i=await b(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await b(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await b(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await b(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await b(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await b(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const s=r(i(87561)),n=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(43414);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(39938),s=i(6314);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},18991:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(84492)),n=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},24948:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const c=i(42748),d=i(87561),h=i(57153),f=i(4866),m=i(39938),p=i(88491),g=i(75556),y=i(61570),v=i(84253),w=i(44726),b=i(21669),S=i(82798),P=i(24945),M=i(19658),_=i(8177),T=i(38307),E=i(91641),D=i(95557),k=i(57510),x=i(82341),C=i(35796),F=i(10408),I=i(53525),A=i(18849),O=i(25015),L=i(98250),R=i(83837),N=i(9483),B=i(43414),j=i(51081),z=i(47987);t.AssetFileSyncStates=(0,v.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,v.strEnum)(...t.AssetFileSyncStates.values,"rejected","failed","timeout","enqueued","started","copied","note"),t.FileDoneStates=(0,_.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,v.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const V={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",unknown:"an internal error occurred during processing."},W={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function U(e){return(0,y.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const q=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function H(){return(0,x.librarySyncReportsDir)()??L.PosixFile.for((0,C.logDir)()).join("sync-reports")}function G(){return H().join("README.txt")}t.SyncReportHeaders=(0,v.strEnum)(...(0,y.keys)(new class{constructor(e,t,i,r,s,n,a,o){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o}}(Date.now(),"","","","",0,"",""))),t.syncReportDir=H,t.syncReportReadme=G,t.ensureSyncReportReadme=(0,f.lazy)((()=>(0,z.writeTextfile_)(G().nativePath,(0,w.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications donโ€™t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${U(W)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${U(V)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=p.dayMs){const t=Date.now()-e;return H().descendants((async e=>(0,O.isCsvExt)(e)&&(0,g.gte)(e.mtimeMs(),t)))},t.syncReport=(0,f.lazy)((()=>new $));class $ extends D.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>this.close()),E.EndableRanks.service),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,0),this.outputFiles=new P.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return l(this,s,"f")?.nativePath}get rowCount(){return l(this,a,"f")}onProgress(e){var i;if(null==e||(0,m.blank)(e.path)||(0,m.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,A.stack)()});{this.logger.log(q.has(e.state)?N.LogLevels.warn:N.LogLevels.info,"onProgress()",e);const r=Date.now(),s={ts:r,at:new Date(r).toISOString(),path:e.path,state:e.state,from:e.from,details:(0,S.toS)(e.details).trim().replace(/\r?\n/g,"; "),url:e.url,elapsedMs:e.elapsedMs},n=(0,h.unparse)([s],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+j.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),u(this,a,(i=l(this,a,"f"),++i),"f")>B.Settings.syncReportMaxRows.valueOrDefault&&this.close()}}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+I.InternalErrorFlag,{path:e,result:n}),(0,t.syncReport)().onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r,stack:r.stack}),this.onProgress({path:e,from:i,state:r instanceof b.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,F.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return l(this,n,"f")??l(this,r,"m",o).call(this)}async close(){const e=l(this,n,"f");return u(this,n,void 0,"f"),u(this,a,0,"f"),await(0,R.endStream)(e),null==e?void 0:l(this,s,"f")}}t.SyncReport=$,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){return u(this,s,function(){const e=c.DateTime.now();return H().join(e.toFormat("y-MM-dd"),(0,k.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(l(this,s,"f").nativePath),this.logger.info("Opening new report: "+l(this,s,"f")),M.isTest&&(0,T.stdoutWrite)({syncReport:l(this,s,"f").nativePath},!1),u(this,n,(0,d.createWriteStream)(l(this,s,"f").nativePath),"f"),l(this,n,"f").write((0,h.unparse)([t.SyncReportHeaders.values],{header:!1})+j.Newline),l(this,n,"f")}},22143:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(70612)),n=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44470)),n=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},43586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(4866),s=i(43947),n=i(66776),a=i(77296),o=i(42041),l=i(4586),u=i(79015),c=i(6231),d=i(43414),h=i(61861),f=i(98250);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},74836:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=n(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),b=i(53719),S=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,S.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function T(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await T(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(r){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:r})}},timeoutMs:(0,b.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await T(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=T},1963:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(49411)),n=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},76333:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(39938),s=i(14889),n=i(95725);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,r.blank)(e)&&(0,n.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(84492),s=i(34996);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},47987:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44470)),n=r(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(87561)),n=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},81286:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(10408),a=i(96593),o=i(83135),l=i(79403);t.exiftoolHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifToolโ€ฆ",settings:[],later:async()=>{try{const e=await(0,a.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,o.ver)(e),(0,r.tt)((0,a.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}catch(e){return{level:"error",msg:"Something's amiss with ExifTool: "+(0,n.errorToS)(e)}}}})))},13699:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(93977),o=n(i(82264)),l=i(11944),u=i(36535),c=i(39938),d=i(43383),h=i(89253),f=i(7162),m=i(91464),p=i(29223),g=i(10156),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,g.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,p.defaultApplePhotosLibrary)()]).sort(),t=new h.MultiMap,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){(0,c.notBlank)(i?.code)&&t.add(i.code,e)}t.delete("ENOTDIR"),t.delete("ENOENT");const r=t.isEmpty()?{level:"ok",msg:["Default media directories are readable","Checked the following directories:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Problem trying to read the following directories:",(0,u.li)((0,m.sortByCaseInsensitive)(t.tuples(),(([,e])=>e)).map((([e,t])=>`${(0,u.tt)(t)}: ${e}`)))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},2882:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(43383),s=i(15203),n=i(13699),a=i(79403);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directoriesโ€ฆ",settings:[],later:n.externalDirectoryCheck})))},91290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(53719),s=i(79403),n=i(32940),a=i(18295);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},79403:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const b=i(4866),S=i(11944),P=i(59694),M=i(43947),_=i(16475),T=i(77125),E=i(66776),D=i(23175),k=i(44726),x=i(20636),C=i(90957),F=i(39784),I=i(82798),A=i(13779),O=i(24945),L=i(94383),R=i(7162),N=i(12308),B=i(34996),j=i(4691),z=i(20681),V=i(70259),W=i(42648),U=i(10408),q=i(49379),H=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Y=i(62905),X=i(18295),Z=(0,b.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,s,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,s,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,s,"f",l).push((0,k.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,s,"f",l).toA()}static addLoadingMsg(e){v(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,S.compact)((0,F.toA)(e)).map(I.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Z().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,s,"f",h).entriesByCountDesc()}),(0,E.map)((0,A.leastBy)(e,(e=>[v(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,s,"f",h).incr(e.msg))),Z().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return H.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return v(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,T.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=s.summary();if(t.settledCountv(s,s,"f",a).enqueue({name:this.id,l:()=>v(this,r,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)H.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>s.onResultChange(),onError:()=>s.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return H.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,x.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,r,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,S.isEmpty)(e))return{};const[t,i]=(0,A.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,S.isNotEmpty)(i)&&(r.links=(0,S.uniqBy)(i)),(0,S.isNotEmpty)(t)&&(r.buttons=(0,S.uniqBy)(t)),r}t.HealthCheck=Q,s=Q,r=new WeakSet,o=function(){return(0,S.filterInPlace)(v(this,s,"f",n),(e=>!e.isPending)),v(this,s,"f",n)},m=function(e){const t=Z().tap({level:"info",msg:"#summary()",result:(0,X.summarizeHealthChecksSync)({errors:v(this,s,"f",l),skipPending:v(this,s,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,s,!0,"f",u),t.state!==v(this,s,"f",c).last?.state&&v(this,s,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Z().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,D.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,r,"m",g).call(this,{level:"disabled",msg:["Disabled by "+H.Settings.skipHealthCheckIds.key]});const i=await(0,x.thenOrTimeoutError)(e(),t);return v(this,r,"m",g).call(this,i)}catch(e){return v(this,r,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=s.normalizeMsg(e.msg),r=e.level??((0,I.toS)(i).toLowerCase().includes("error")?"error":(0,I.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),n=(0,S.compact)([...e?.links??("ok"===r||"pending"===r?this.okLinks:"warn"===r?this.warnLinks:"no-library"===r?this.noLibraryLinks:"error"===r?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:r,elapsedMs:this.result.elapsedMs(),msg:i,...ee(n)};return(0,j.ending)()?a:this.logger.tap({level:Y.HealthCheckLevelToLogLevel[r],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,k.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,q.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,r,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},n={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new O.BoundedList(10)},u={value:!1},c={value:new O.BoundedList(10)},d={value:new O.BoundedList(100)},h={value:new L.CountingSet},f={value:[]},Q.all=(0,b.lazy)((()=>Object.freeze((0,P.sortBy)(v(s,s,"f",f),(e=>e.sortBy))))),Q.summary=(0,b.lazy)((()=>v(s,s,"m",m).call(s))),Q.resetDebounced=(0,N.debounce)((()=>s.reset()),50)},90524:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},6565:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(84253);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(36535),s=i(77125),n=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},46747:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(4866),s=i(36535),n=i(43383),a=i(77125),o=i(7162),l=i(19658),u=i(29405),c=i(79015),d=i(82041),h=i(81286),f=i(2882),m=i(79403),p=i(61099),g=i(71664),y=i(28482),v=i(22627),w=i(32940),b=i(17938),S=i(40715),P=i(11560),M=i(44454),_=i(93763),T=i(97596),E=i(74113),D=i(23119),k=i(59415),x=i(20610),C=i(9335),F=i(12358),I=i(84729),A=i(42386),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test checkโ€ฆ",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,k.settingsSystemHealthCheck)(),(0,D.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,M.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,_.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,I.videoHealthCheck)(),(0,A.volumeHealthCheck)(),(0,F.versionHealthCheck)(),l.isProd||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},61099:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(71923),u=i(15203),c=i(83135),d=i(79403);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC toolingโ€ฆ",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},71664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(66776),a=i(10408),o=i(22143),l=i(15299),u=i(49849),c=i(83135),d=i(79403);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"โ€ฆ",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK","jpegtran is a supported version.",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},91499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(11944),s=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},28482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(24586),l=i(82341),u=i(10408),c=i(3955),d=i(15203),h=i(51053),f=i(43414),m=i(82041),p=i(32421),g=i(79403),y=i(91499);async function v(){const e=await(0,l.setupLibraryDirs_)();return(0,m.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}async function w(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(f.Settings.libraryDir.toEnvLine(f.Settings.libraryDir.defaultValue))}`]};const t=await(0,p.mountpoints_)(),i=(0,c.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[y.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`];return null!=t&&(0,a.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}return await v()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}.`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}}async function b(){const e=(0,l.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:"No PhotoStructure library is open"};if(!(0,m.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",f.Settings.libraryDir.hasValue()?(0,r.tt)(f.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await v():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${h.isWin?"":"/execute"} by ${await(0,o.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,o.userDesc)()}`,(0,u.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}t.libraryDirectoriesCheck=(0,n.defer)((()=>g.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directoriesโ€ฆ",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,d.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:(0,d.isDocker)()?w:b})))},22627:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(75556),l=i(61570),u=i(17078),c=i(82341),d=i(42648),h=i(43414),f=i(46573),m=i(79403);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)โ€ฆ",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},32940:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(70612)),n=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},17938:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(97742)),n=i(36535),a=i(43383),o=i(46954),l=i(83135),u=i(79403);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.jsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},40715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(43383),s=i(27175),n=i(51053),a=i(79403);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directoryโ€ฆ",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},11560:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(43383),s=i(55463),n=i(79403);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating systemโ€ฆ",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},44454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(10408),a=i(51053),o=i(71663),l=i(83135),u=i(79403);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShellโ€ฆ",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},93763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(34879),a=i(10408),o=i(83135),l=i(79403);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLiteโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},97596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(75556),o=i(24586),l=i(42648),u=i(29405),c=i(60052),d=i(51053),h=i(79403);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission levelโ€ฆ",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},74113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(17078),a=i(43414),o=i(77016),l=i(79403);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},23119:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(43383),s=i(82041),n=i(79403),a=i(59415);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settingsโ€ฆ",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},59415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(11944),s=i(36535),n=i(43383),a=i(17078),o=i(91464),l=i(10408),u=i(98250),c=i(82041),d=i(98024),h=i(79403);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settingsโ€ฆ",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},20610:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=t.sharpHealthCheck=void 0;const s=r(i(39084)),n=i(71017),a=r(i(57441)),o=i(43383),l=i(24603),u=i(87748),c=i(61570),d=i(10408),h=i(27175),f=i(79403);async function m(e){const t=e??(0,n.join)(h.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(t,{failOn:"error"}),r=await i.resize(31,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,l.eql)((0,c.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:31,height:32,channels:3}),"Unexpected sharp output: "+(0,u.stringify)(r.info))}t.sharpHealthCheck=(0,o.defer)((()=>f.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharpโ€ฆ",settings:[],later:async()=>{try{return await m(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,d.errorToS)(e)]}}}}))),t.testSharp_=m},18295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(11944),s=i(88491),n=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},9335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(36535),s=i(88491),n=i(43383),a=i(75556),o=i(43414),l=i(11053),u=i(79403);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system loadโ€ฆ",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},12358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(88491),s=i(43383),n=i(57310),a=i(79403);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure versionโ€ฆ",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},84729:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(36535),s=i(43383),n=i(43947),a=i(66776),o=i(79015),l=i(46517),u=i(15203),c=i(83135),d=i(79403);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video toolingโ€ฆ",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},42386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(20636),l=i(17078),u=i(13779),c=i(14889),d=i(51053),h=i(7903),f=i(69551),m=i(53719),p=i(46573),g=i(79403);t.volumeHealthCheck=(0,a.defer)((()=>g.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumesโ€ฆ",settings:[],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:d.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,p.volumes)(),(0,m.commandTimeoutMs)());if(i===o.Timeout){const i=await(0,o.thenOrTimeout)(d.isWin?(0,f.getLocalVolumesWin_)():(0,h.dfPosixRawLocal_)(),c.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===o.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following mountpoints:",(0,s.li)(a.map((e=>e.mountpoint)))]};const[g,y]=(0,u.partition)(i,(e=>!0===e.remote));return{level:"ok",msg:["Volumes seem OK",(0,l.plur)(y.length,"local volume")+" and "+(0,l.plur)(g.length,"remote volume")+" checked."]}}})))},65564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),b=i(21084),S=i(98250),P=i(23872),M=i(74836),_=i(4416),T=i(47874),E=i(43414),D=i(96593),k=i(95011),x=i(49312),C=i(36810),F=i(87062),I=i(80870),A=i(14489),O=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,D.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const L=(0,s.lazy)((()=>new b.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:L});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const r=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==r){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(r);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:r,whyRejected:e})}const s=i.sha??await r.sha();if(null!=s)if(!0!==await(0,t.isBadSha)(s))try{return await this._build(r,i)}catch(t){e.push(t),L().set(s,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",r);else this.logger.info("skipping: cannot read SHA",r),e.push(new Error("Cannot read "+r.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,O.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:a,height:o,sha:l,mimetype:u}=t;if(null==s||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,n.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const a=(0,k.fitSizes)(e,e.mimetype),o=(0,n.diff)(r,s);if((0,n.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,k.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),b=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,d.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of u){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&r.reducer===I.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(r)+" -> "+(0,l.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(13783),s=i(57743),n=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(84253);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},37251:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(57441)),n=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},7218:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(4866),s=i(75556),n=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(11944),s=i(57743),n=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(39938),s=i(43947),n=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:n.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(39938),s=i(82798),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},49441:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(93977),s=i(4866),n=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(57441)),n=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),b=i(95725),S=i(7162),P=i(48446),M=i(43414),_=i(13378),T=i(27446),E=i(68107),D=i(37251),k=i(34928),x=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const I=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function A(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:I,impl:A}),t._imageHash_=A,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},32148:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(38625),o=i(57743),l=i(51367),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(33714),m=i(13779),p=i(7162),g=i(70283),y=i(81108),v=i(6451),w=i(30072),b=i(60346),S=i(1482),P=i(6667),M=i(48446),_=i(43414),T=i(34928),E=i(72461),D=i(36143),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function I({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function A(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=I({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=I({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=I({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),A=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(v)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=A,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:A,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=I,t.isSimilarImage=A,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return A(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},36810:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},87062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},34956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matchAndWriteRotation_=t.matchRotation=void 0;const r=i(4866),s=i(61570),n=i(33714),a=i(7162),o=i(7383),l=i(96593),u=i(31195),c=i(84685),d=i(72461),h=i(32148),f=(0,r.lazy)((()=>(0,a.mkLogger)("img.MatchRotation")));async function m(e,t){return(0,o.time)("img.matchRotation",(async()=>{const i=await(0,d.imageHash)(e),r=await(0,d.imageHash)(t),s=(0,h.compareImageHashes)(i,r);if(null!=i&&null!=r&&null!=s)return f().tap({level:"info",msg:"matchRotation()",result:{rotation:s.bRotation,exemplarImageHash:i,destImageHash:r,imageHashComparison:s},meta:{src:e,dest:t}});f().warn("failed to compute image hashes",{a:e,b:t})}))}t.matchRotation=m,t.matchAndWriteRotation_=async function(e,t,i=0){const r=await m(e,t);if(null==r)return;const a=(0,n.normalizeRotation)(r.destImageHash.rotation+r.rotation+i);if(f().info("matchRotation() computed newRotation",{currentRotation:r.destImageHash.rotation,additionalRotation:i,rotationToMatch:r.rotation,newRotation:a}),null==a)return void f().warn("Can't compute final orientation",{newRotation:a,file:t.nativePath,r});const o=(0,c.rotationToWriteTag)(a);if((0,s.isEmptyObj)(o))return void f().warn("rotationToWriteTag() returned null",{newRotation:a,mimetype:r.destImageHash.mimetype,file:t.nativePath});const d=await(0,u.ensureHistoryRecords)(await t.sidecar(),(0,u.mkHistoryRecords)(u.Actions.set,o));return await(0,l.writeTags_)(t,o),f().tap({level:"info",msg:"matchAndWriteRotation_()",result:{...r,writtenTags:o,rotation:a,historyRecords:d},meta:{exemplar:e,dest:t}})}},58061:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(57441)),n=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},35254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(4866),s=i(18941),n=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(4866),s=i(66776),n=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(11944),s=i(57743),n=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},53026:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(4866),s=i(75556),n=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(4866),s=i(57743),n=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(57441)),n=i(4866),a=i(7162),o=i(43414),l=(0,n.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(84253);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(889),n=r(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),b=i(79141),S=i(98250),P=i(95725),M=i(43414),_=i(96593),T=i(27446),E=i(84685),D=i(15465),k=i(68107),x=i(53719),C=i(59387),F=i(34928),I=i(71923),A=i(49312),O=i(49441),L=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),j=(0,a.lazy)((()=>{n.default.simd(M.Settings.enableSIMD.valueOrDefault),n.default.cache(M.Settings.enableVipsCache.valueOrDefault),n.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function z(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=z,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=B().addParameterContext(e.nativePath);j();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),O=(0,h.lt)(C,1),L=(0,T.isSharpMimeType)(n)&&null==t,z=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||O||L||z)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:O,isSharpMimeAndNoMinDim:L,isMirrorOrientation:z});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,n,t,x,C)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,I.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,I.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const r=i(43649),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=s.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*s.secondMs},p1:{x:20*o.MB,y:12*s.secondMs}},p={p0:{x:11*o.MB,y:12*s.secondMs},p1:{x:26*o.MB,y:24*s.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,s=(0,f.commandTimeoutMs)(),n=e.bytes/f.MinIoRate,u=t=>(0,r.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+s+n+c+d),dbMs:i,tagMs:s,copyMs:n,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,r.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,n.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(57441)),n=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),b=i(23024),S=i(14489),P=i(46517),M=i(15299),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(4866),s=i(11944),n=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(4866),s=i(11944),n=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),b=i(79015),S=i(21084),P=i(98250),M=i(95725),_=i(43649),T=i(6667),E=i(49586),D=i(43414),k=i(68567),x=i(27947),C=i(96593),F=i(27446),I=i(84685),A=i(68107),O=i(53719),L=i(7218),R=i(49441),N=i(12737),B=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function j(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function z(e){return h.isProd&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const r=j("extractMaxBitrate",e),s=D.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,k.extractBitrateKbps)(i)??D.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=z,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await z())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:D.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:D.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,r.lazy)((()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=j("extractVideoFrame",e),r=P.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,R.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,I.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,L.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,x.extractDurationSec)(l),m=Math.min(f??0,D.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,O.commandTimeoutMs)()}),s.nativePath}async function H(){return D.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=j("needsTranscoding",e);if(!await H())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,x.extractDurationSec)(i);if(!(0,c.gt)(n,D.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(D.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=H,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await H())return;const r=j("transcode",e),s=$.get(t.nativePath);if(null!=s&&!(0,n.isTrue)(i?.force))return r.info("already transcoding",{dest:t,priorSrc:s.name}),s.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void r.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return r.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return r.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),r=await(0,C.readRawTags)(e),s=(0,x.extractDurationSec)(r),n=(0,x.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return r.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,x.extractDurationSec)(d)??60,s={src:e,...V(e,d)},n=J(o,s.videoBitrateKbps,i),a=D.Settings.transcodeMaxDim.valueOrDefault,h=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?r.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(s.width=(0,u.roundEven)(e.width),s.height=(0,u.roundEven)(e.height),r.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{r.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},n,(async()=>await t.clear().size()??0));s.dest=i,s.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(s));0!==o.code&&r.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&j("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),b=i(43414),S=i(49849),P=i(53719),M=i(33185),_=i(5023),T=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:b.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const D=/ffmpeg version n?(?\S+)/i,k=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:b.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=D.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){k.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...b.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(b.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function I(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=b.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(k(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",x),(0,y.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await k.prior()??k.refresh()},t.isFFmpegSupported=async function(){return null!=await k()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...A(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...I(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,g.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??b.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const r=i(75556),s=i(4866),n=i(43414),a=i(59387);t.ffmpegThreads=(0,s.lazy)((()=>(0,r.toGt0)(n.Settings.ffmpegThreads.value)??(0,r.clamp)(1,6,(0,r.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(4866),s=i(88491),n=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),b=i(7218),S=i(49441),P=i(36810),M=i(59430),_=i(33185),T=(0,r.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return T().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,S.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],D=["-Z","-"],k=["-o","1"],x=["-t","0","-j"];async function C(e,t){const i=Date.now(),r=await(0,b.dimensions)(e);if(null==r)return T().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(r),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(r)&&(T().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),S=[...E,...D,...k,...v,...x,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*n.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};T().debug("dcraw_emu()",{cmd:w,args:S,opts:F});const I=(0,d.execFile)(w,S,C,F),A=[];function O(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))T().info("dcraw_emu(): warning",{src:e,msg:i});else{T().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});A.push(r)}}I.on("error",O),I.stderr.on("data",O);const L=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},L,(()=>Date.now()-i));if(I.on("close",(()=>R.end())),await t.writeStream_(I.stdout),(0,s.isNotEmpty)(A))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:A,path:e.nativePath});(0,d.endProcess)(I)}t.dcraw_emu_=C},16114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(4866),s=i(69317),n=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},10508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(65628);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},49857:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(39938),s=i(43414),n=i(69060);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},33501:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(35666),s=i(11944),n=i(88491),a=i(8199),o=i(13779),l=i(70283),u=i(69060),c=i(73435);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},69060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(4866),s=i(59694),n=i(39938),a=i(38625),o=i(43383),l=i(43947),u=i(1429),c=i(66776),d=i(75556),h=i(44726),f=i(35666),m=i(22840),p=i(39784),g=i(82798),y=i(9678),v=i(7162),w=i(46852),b=i(80294),S=i(4586),P=i(82341),M=i(42648),_=i(79015),T=i(98462),E=i(43414),D=i(10508),k=i(33501),x=i(19842),C=i(13700),F=i(74916);t.k=(0,r.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function A(e){const i=await(0,x.V)((0,h.ensurePrefix)((0,g.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,d.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,g.toS)(i.uids).split(","),i}async function O(e,i,r,s){try{return(0,n.blank)(e)?void 0:k.L.for({str:e,l:await A(e),sids:null!=s?s:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function L(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await O((0,p.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function R(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function N(){return(await R())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=A,t.v=O,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await O(e,t,i);return(0,a.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,r.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,c.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),r=(n=(0,u.flatten)((await(0,w.someOrTimeout)([()=>function(e){return O(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,y.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,s.sortBy)(n.filter((e=>null!=e&&((0,m.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,m.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:r})})),(0,l.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset()))})),t.b=R,t.t=N,t.l=async function(){try{return await N()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await N()===(0,t.k)().g}catch{return!1}}},19842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91144),s=i(4866),n=i(39938),a=i(10508);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},73435:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(11944),a=i(59694),o=i(39938),l=i(43383),u=i(84253),c=i(82798),d=i(94383),h=i(4866),f=i(7162),m=i(29731),p=i(6231),g=i(10508),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},13700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(43383),o=i(1429),l=i(61570),u=i(44726),c=i(39784),d=i(82798),h=i(7162),f=i(19658),m=i(46852),p=i(69317),g=i(51081),y=i(16958),v=i(4931),w=i(43586),b=i(9483),S=i(72612),P=i(51053),M=i(71663),_=i(46573),T=i(75153),E=i(10508),D=i(73435);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function A(){return P.isLinux?(await I("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await I("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await I("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,A,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if(f.isTest)for(const t of e)H.add(t)},t.clearSids=function(){f.isTest&&H.clear()}},74916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(88491);t.UserTimeoutMs=7*r.secondMs},59714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const r=i(43383),s=i(66776),n=i(7162),a=i(29731),o=i(46852),l=i(4586),u=i(82341),c=i(56958),d=i(98462),h=i(33501),f=i(69060),m=(0,r.defer)((()=>(0,n.mkLogger)("writeLicense")));async function p(e,t){return(await(0,o.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,f.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof h.L))}async function g(e,t,i){if(null!=t)if((await p(t,i)).some((t=>t.cmp(e)>=0)))m().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,a.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,c.broadcastEvent_)("reloadLicenses"),m().info("saveIfBetter(): wrote to "+i),i}catch(e){return void m().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,f.vok)(e,"candidate",t);if(null==i)return m().error("!ok",e);await g(i,(0,u.libraryDataDirPosixFile)()?.join((0,f.k)().d),t),await g(i,(0,s.map)((0,l.configDir)(),(e=>d.BaseFile.for(e).join((0,f.k)().d))),t),await f.m.refresh()},t.licensesInDirectory=p,t.saveIfBetter=g},7157:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(11944),s=i(88491),n=i(43947),a=i(1429),o=i(61570),l=i(8199),u=i(26588),c=i(59390),d=i(7162),h=i(70259),f=i(21142),m=i(10408),p=i(57400),g=i(43414),y=i(77200),v=i(9483),w=i(13755),b=i(92781);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},14235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(47261),s=i(4866),n=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},74269:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(4866),s=i(55568),n=i(95976),a=i(98968);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},78109:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(39938),s=i(16475),n=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,n.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(7162),s=i(81026);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},71951:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(4866),s=i(27998);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},88777:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},7258:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},85352:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(49411),s=i(88491),n=i(43414);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},84235:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(4866),s=i(88491),n=i(55568),a=i(27522),o=i(25015),l=i(43414);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isExt)(e.ext,".log",".log.gz")})))},77200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(59694),s=i(75556),n=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(4866),s=i(9483);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const n=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],r.set(this,(0,n.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>s(this,r,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap},9483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(88491),s=i(75556),n=i(84253);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,s.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*r.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(11944),s=i(61570),n=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},13755:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(87561),h=i(65628),f=i(81666),m=i(40374),p=i(94329),g=i(55413),y=i(77200),v=i(53208);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.store[0]:void 0}shift(){const e=this.lines.store.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},55248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(87561),s=i(49411),n=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),b=i(95557),S=i(4691),P=i(70259),M=i(80294),_=i(10408),T=i(57400),E=i(3955),D=i(43414),k=i(71951),x=i(85352),C=i(81647),F=i(95976),I=i(9483),A=i(98968),O=i(53208);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,A.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,A.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,A.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,A.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,A.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(55413),s=i(58623),n=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),b=i(55568),S=i(91464),P=i(28807),M=i(91641),_=i(93033),T=i(40374),E=i(83837),D=i(43414),k=i(74269),x=i(85352),C=i(81647),F=i(95976),I=i(48924),A=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,s,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,A.recentLogEntries)()),(0,A.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(47261),s=i(11944),n=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},53208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(39938),s=i(51081),n=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},94679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(4866),s=i(59694),n=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(49411),s=i(4866),n=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),b=i(7258),S=i(95976),P=i(98741),M=i(55248),_=i(81026),T=i(27998);t.setupLogger=(0,s.lazy)((()=>{(0,S.logFilter)()instanceof P.LogFilterImpl||S.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const s=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&s.push(y.ConsoleLogger.instance()),(0,n.map)((0,b.logBroadcaster)(),(e=>s.push(e))),l.rootLoggers.set(s),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>S.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,s.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new T.PlaintextLogFormatter)}));const E=(0,s.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},92781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(4785);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},60346:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,s=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(11944),s=i(66776),n=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},25506:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(59694),s=i(89965);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(59694);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(11944),s=i(75556),n=i(13779),a=i(60346),o=i(6667);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},72755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(59694),s=i(88491),n=i(75556),a=i(33912),o=i(59873),l=i(81765),u=i(6231);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},6231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(6005),s=i(39938),n=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(75556),s=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},1482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(33714);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}ร—${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(6005),s=i(3331);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(65628),s=i(39938),n=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},38786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableServer=void 0;const r=i(36079),s=i(91641),n=i(83837);t.EndableServer=class{constructor(e,t){this.name=e,this.server=t,this._ended=!1,(0,r.addEndable)(s.EndableRanks.service,this)}get ended(){return this._ended}end(){return this._ended=!0,(0,n.closeStream)(this.server)}}},18501:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(70612)),n=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},72612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(70612),s=i(4866),n=i(11944),a=i(39938),o=i(88491),l=i(1429),u=i(75556),c=i(61570),d=i(7162),h=i(91464);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},58659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(30604),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function S(e){return null!=b.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=S,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=P(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(S(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!S(e)||!S(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(39938),s=i(88491),n=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},95487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(11944),s=i(39938),n=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(87561),s=i(38625),n=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(49411),s=i(4866),n=i(82798);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(43383),s=i(7162),n=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(70612)),n=r(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(87561)),n=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(39938),s=i(44726),n=i(63774);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(4866),s=i(11944),n=i(61570),a=i(7162),o=i(86780),l=(0,r.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const a of t)for(const[t,o]of(0,n.entries)(a)){const n=await o(e);!0===n?i.push(t):!1===n?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{if(!1===await r(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await u.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(61570),s=i(86780);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},24409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(11944),s=i(39938),n=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(4866),s=i(88491),n=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(87748),s=i(75556),n=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(75556),s=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(5712),s=i(4866),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),b=i(21142),S=i(69317),P=i(79015),M=i(51053),_=i(43414),T=i(53719),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(84253);t.AggregateTypes=(0,r.strEnum)("union","intersection")},92187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(84253);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(39938),s=i(38625),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(84253);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(42885),s=i(77696),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38625),s=i(61570),n=i(84253),a=i(43414),o=(0,n.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,s.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,s.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,r.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},27644:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(4866),s=i(39784),n=i(9678),a=i(4586),o=i(98250),l=i(7162),u=i(84161),c=i(43414),d=i(82041),h=i(85560),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},23830:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(4866),s=i(39938),n=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,r.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function b(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function S(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&b(),w("strictDeduping",e)&&S(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&D()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(g.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=b,t.setStrictDeduping=S,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?T:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function D(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=D},29909:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(39938),s=i(35008),n=i(99088);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(39938),s=i(75556),n=i(84161);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},83773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(42748),s=i(4866),n=i(11944),a=i(39938),o=i(66776),l=i(44726),u=i(7162),c=i(91464),d=i(76387),h=i(45161),f=i(60299),m=i(3955),p=i(43414),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+(0,l.replaceAll)(e,"'","โ€ฒ")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(44726),s=i(63774);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const r=i(4866),s=i(11944),n=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),b=i(84490),S=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,r.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,n.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,s.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,n.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,s.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,b.envFromName)(e),this._keys=(0,s.uniq)([...this._names.map(b.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return S.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,n.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),r=this.envValue??t;return null!=r&&(i[this.key]=this.opts.toEnv(r)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,s.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+r],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(84253);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(5712),s=i(49411),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),b=i(86725),S=i(6344),P=i(42885),M=i(27387),_=i(29393),T=i(94794),E=i(7560),D=i(45005),k=i(20902),x=i(6565),C=i(80534),F=i(86613),I=i(15203),A=i(51053),O=i(33407),L=i(11579),R=i(82590),N=i(55267),B=i(98788),j=i(61659),z=i(40185),V=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Y=i(29712),X=i(26764),Z=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),re=i(7043),se=i(29909),ne=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,n.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new ne.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new re.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new re.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new re.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new re.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new re.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new re.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new re.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:A.isWin?["proc-not-superuser"]:[],strEnum:x.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new re.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new re.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,O.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new re.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new re.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new re.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new re.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,O.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new re.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new re.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Z.ColorDistanceFunctions.ciede2000,strEnum:Z.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new re.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new re.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new re.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new re.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>S.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new re.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:se.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:L.DateTagFormats.ym,strEnum:L.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:j.KeywordReparentingStrategies.move,strEnum:j.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:z.NameTagFormats["as-is"],strEnum:z.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(s.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(s.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,n.lazy)((()=>ve((0,k.getEnv)("PATH")))),t.allSettings=(0,n.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,n.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,n.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const be=(0,n.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return be().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,n.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(4866),s=i(19658),n=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=n.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>s.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:s.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),b=i(91464),S=i(63774),P=i(42041),M=i(82341),_=i(10408),T=i(79015),E=i(98462),D=i(98250),k=i(38846),x=i(23830),C=i(84161),F=i(44911),I=i(43414),A=i(95699),O=i(85560),L=i(98024),R=i(13060),N=i(31086),B=i(16704),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,M.libraryDataDirPosixFile)(e)?.join(O.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,L.systemSettingsFile)()))?.[I.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,L.systemSettingsFile)())}async function q(e){return(0,m.map)(z(e),(e=>J(e)))}function H(){t.libraryHasSettings.refresh()}function G(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:I.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return I.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Y()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await q()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",H),(0,T.ee)().on("settingsChanged",H),I.Settings.libraryDir.watchLater(H)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...re("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:r}),r){const t=await(0,R.readTomlFile_)(s),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"old"}),await s.unwip_())}}async function Y(e=(0,L.systemSettingsFile)()){const t=D.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,I.persistedSystemSettings)()),t}function X(e){return Q(z(e))}async function Z(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,I.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,I.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,R.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{const i=(0,I.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,I.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;n.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.versionForSettings=(0,r.lazy)((()=>P.version)),t.writeSystemSettings_=Y,t.writeAllSettings_=function(e){return K(D.PosixFile.for(e),(0,I.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Z,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,r.lazy)((()=>new Set([I.Settings.httpPort,I.Settings.license,I.Settings.logStdout,I.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(I.Settings))te().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function re(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),I.Settings.libraryDir.unset(),await Y()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(D.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(D.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...re("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...re("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...re("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...re("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...re((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(49411),s=i(11944),n=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["ยฆ",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(84161);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},39165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(11944),s=i(87748),n=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(39938),s=i(91464),n=i(84161);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(49411),s=i(66776),n=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(84253);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},13060:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(81627),s=i(44470),n=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(39938),s=i(1429),n=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(87748);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},77016:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(61570),s=i(91464),n=i(29405),a=i(60052),o=i(43414);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a)null==a.value.opts.fromEnv(r)&&i.push({envKey:n,msg:`The value "${e[n]}" isn't valid for this ${a.value.constructor.name}.`});else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},16704:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(82798),s=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(81666),s=i(91464);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),b=i(85590),S=i(45161),P=i(23595),M=i(46175),_=i(50140),T=i(68074),E=i(54809),D=i(64455),k=i(60299),x=i(3955),C=i(95725),F=i(63410),I=i(9483),A=i(43414),O=i(69301),L=i(82590),R=i(63526),N=i(26352),B=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function z(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=z,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,S.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);z(this.src)&&(t=Math.max(A.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,S.datedToISO)(this.date)}toExifString(){return(0,S.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!z(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,S.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?A.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:A.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function U(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||L.OverrideUTCZoneTags.includes(s))){t=(0,S.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,w.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function q(e,t){if(A.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function H(e){if(A.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(A.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,S.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!A.Settings.usePathsToInferDates.valueOrDefault||!A.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,x.containedByNativePath)({ancestor:A.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",U(t,A.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??s("tags",U(t,A.Settings.capturedAtTagsFallback.values))??(n?void 0:s("bname+stat",await(0,N.extractStatBname)(e)))??(n?void 0:s("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",q(e,t)))??(n?void 0:s("path",H(e)))??(A.Settings.useStatToInferDates.valueOrDefault?s("stat",await G(e)):void 0);return B().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,A.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=H,t.capturedAtFromStat=G},11579:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(84253);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},82590:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(75556),s=i(70283),n=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(889),n=r(i(49411)),a=r(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),b=i(37121),S=i(13056),P=i(55170),M=i(45161),_=i(23595),T=i(84593),E=i(21084),D=i(98250),k=i(95725),x=i(76531),C=i(7162),F=i(76474),I=i(19658),A=i(2023),O=i(55568),L=i(43414),R=i(13378),N=i(14889),B=i(91464),j=i(53719),z=i(59387),V=i(65642),W=i(27947),U=i(74873),q=i(45581),H=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Y=i(91854),X=i(54988),Z=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),re=i(26352),se=i(45023),ne=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:L.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,...(0,S.batchClusterOptions)((0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeout)(e.version(),(0,j.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,Z.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Z.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Z.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,A.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,A.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Z.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l),(0,f.assignFields)(n.inferred,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};I.isTest&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,A.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(n.default.extname(e))?[]:void 0,r=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Z.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},74873:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(39938),s=i(82798),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(4866),s=i(39938),n=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(84253);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(4866),s=i(11944),n=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),b=i(85590),S=i(54809),P=i(3955),M=i(98250),_=i(95725),T=i(43414),E=i(96593);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function A(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),A(i,s,n)},t.ensureHistoryRecords=A},92330:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(9160)),n=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function b(e,t,i){{const e=S(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function S(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i),r=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:r,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,l.toDated)(t[r]);if(null==s||(0,h.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await b(e,t,i)})},t.zoneFromLatLon=S,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(889),s=i(11944),n=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(84253);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},28033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(889),s=i(25861),n=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},84418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(889),s=i(4866),n=i(11944),a=i(59694),o=i(39938),l=i(66776),u=i(75556),c=i(61570),d=i(2934),h=i(39784),f=i(82798),m=i(9678),p=i(7162),g=i(47003),y=i(85590),v=i(23595),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},27446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(39938),s=i(82798),n=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(84253);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(84253);t.NameTagOrders=(0,r.strEnum)("western","eastern")},84685:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(33714),s=i(82798),n=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(66776),s=i(75556),n=i(43414);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(4866),s=i(39938),n=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(11944),s=i(39938),n=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,n.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,r.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,r.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=n(e.slice(r.length)),l=n(i.slice(r.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(4866),s=i(39938),n=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},59553:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(82798),s=i(61473);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},26352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(889),s=i(42748),n=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),b=i(23595),S=i(60299),P=i(85943),M=i(56640),_=i(21084),T=i(98250),E=i(75123),D=i(95725),k=i(9483),x=i(43414),C=i(96879),F=i(69301),I=i(65642),A=i(96593),O=i(17310),L=i(54988),R=i(27446),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,A.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7){if(!await j(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),s=(0,D.findFileIndex)(e,r);if(s<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const n=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=n&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=n&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,A.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(11944),s=i(39938),n=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(49411),s=i(47261),n=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=(0,o.orElse)(s,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(4866),s=i(11944),n=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(49411),s=i(39938),n=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(11944),s=i(39938),n=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},30848:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},47044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(39938),s=i(88491),n=i(81765),a=i(29731);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},33611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(4586),s=i(98250);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},38846:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(42041),s=i(39036);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},49849:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(10912),s=i(39938),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},73037:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(82798),s=i(13779),n=i(49849),a=i(39036);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},17953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(61570),s=i(44726),n=i(39036);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},39036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(84253);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},83135:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(39938);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},57310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.systemUserAgent=t.userAgent=t.checkVersion_=t.currentChannel=void 0;const r=i(11944),s=i(36535),n=i(88491),a=i(43383),o=i(19067),l=i(9678),u=i(54883),c=i(7162),d=i(55463),h=i(14889),f=i(42041),m=i(20681),p=i(4586),g=i(76531),y=i(69060),v=i(43414),w=i(53719),b=i(15425),S=i(33611),P=i(38846),M=i(73037),_=i(17953),T=i(39036),E=i(83135),D=(0,a.defer)((()=>(0,c.mkLogger)("VersionCheck")));async function k(){return v.Settings.allowUserAgent.valueOrDefault?x():l.SimpleAppName}async function x(){return l.SimpleAppName+"/"+f.version+" ("+(0,d.osFullName)()+") "+(0,u.EditionType)().toLowerCase()+"/"+await(0,y.t)()}t.currentChannel=function(){const e=[v.Settings.updateChannel.valueOrDefault,(0,P.channel)()].map((e=>T.UpdateChannels.ordinal(e))).sort()[0];return T.UpdateChannels.values[e]??v.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(!v.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===v.Settings.optOut.value?e.push("Set "+(0,s.tt)(v.Settings.optOut.toEnvLine(!1))+" to enable."):!1===v.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(v.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,p.configDir)();if(null==i||!await(0,g.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const l=e?.installedVersion??f.version,c=(0,T.extractUpdateChannel)(l),d=(0,T.eligibleForChannel)(c),h=a.versions.filter((e=>d.includes(e.channel))).map((e=>e.version)),m=e?.latestVersion??(0,M.semverLatest)(...h);if(null==m)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+v.Settings.updateChannel.toEnvLine()]};const y=(0,T.extractUpdateChannel)(m),w="You are running "+(0,u.EditionName)()+" "+(0,E.ver)(l),b="The latest published "+(0,s.tt)(y)+" build is "+(0,E.ver)(m),S=y===c?void 0:"You should consider switching to the "+(0,s.tt)(y)+" channel.",P=Date.now()-a.updatedAt,_="Last checked "+(P{const e=(0,S.channelVersionsCache)(),i=await(0,b.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",config:{headers:{"User-Agent":await k()},timeout:h.ShortCommandTimeoutMs},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:f.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,_.isUpdateChannelVersion)(e)))||r.updatedByVersion!==f.version){if(i.fromCache)return D().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();D().throw("getChannelVersions_(): Invalid response",{result:r})}return D().tap({msg:"getChannelVersions_()",result:r})}})},39206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(11944),s=i(14195),n=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},36974:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(3874),s=i(55412),n=i(46573);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},86115:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(4866),s=i(39938),n=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),b=i(49829),S=i(76019),P=i(53719),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await A()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function A(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(I)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=A},36736:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),b=i(76531),S=i(15203),P=i(51053),M=i(7903),_=i(55412),T=i(62255),E=i(53719);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))}),(0,E.mountpointsTtlMs)(),(()=>D().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>D().log((0,s.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(4866),s=i(92585),n=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(4866),s=i(11944),n=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(55543),s=i(4866),n=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(4866),s=i(11944),n=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),b=i(17875),S=i(56958),P=i(79015),M=i(95725),_=i(76531),T=i(51053),E=i(43414),D=i(39206),k=i(36736),x=i(62255),C=i(49829),F=i(10609),I=i(53719),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function O(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){O(),(0,h.isSyncService)()&&await(0,S.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(O),E.Settings.scanPaths.watchLater(O),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux&&(await(0,x.maybeWatchProcMounts)(),await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?C.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,D.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,M.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),O()})),E.Settings.mountpointsTtlMs.watch(L)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(4866),s=i(11944),n=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),b=i(32421),S=i(10609),P=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,S.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=T){if(g.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,r.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:n.minuteMs,onChange:()=>{P().info("detected change in "+M),b.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(4866),s=i(88491),n=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(4866),s=i(39938),n=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(39938),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(11944),s=i(39938),n=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>T())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,d.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,y.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(88491),s=i(17078),n=i(43414);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},27127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),b=i(53719),S=i(21954),P=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,b.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,r.basename)(e.mountpoint)}function T(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,b.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),r=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=r)return P().tap({msg:"Serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,S.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,b.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,b.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=T,t.readUuidFile_=E,t.readVolumeUUID=D},46573:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(70612)),n=r(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),b=i(13779),S=i(7162),P=i(19658),M=i(55568),_=i(91710),T=i(14889),E=i(91464),D=i(46852),k=i(37121),x=i(1629),C=i(14195),F=i(42648),I=i(29405),A=i(20902),O=i(17875),L=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),j=i(98250),z=i(95725),V=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Y=i(55412),X=i(11142),Z=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),re=i(27127),se=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=s.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([j.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){se().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,D.mapAsync)({name:"readCachedVolumes",arr:(0,D.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:r,os:ne}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))n.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){se().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));se().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return se().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function pe(e,i){const r=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(r))return;const s=await(0,R.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return se().debug("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return se().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function ge(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,U.friendlyname)(e);return(0,D.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(n,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return se().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return se().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,O.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return se().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(se().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void se().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,O.onError)("Timed out getting local volume metadata")));if(null==e)return void se().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,D.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;se().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){se().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,O.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,re.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return se().debug("_volumes(): final result",{sorted:r}),r.forEach(ce),await fe(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,b.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(se().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,D.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(49411),s=i(4866),n=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},232:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkEventStream=void 0;const r=i(39938),s=i(87748),n=i(37086);t.mkEventStream=function(...e){let t="";for(const i of e)null!=i&&((0,r.blank)(i.event)||(t+="event: "+i.event+"\n"),t+="id: "+(i.id??(0,n.uid)())+"\n",t+="data: "+(0,s.stringify)(i.data)+"\n",t+="\n");return t}},17679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(84253);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},15425:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const s=r(i(52167)),n=i(43383),a=i(75556),o=i(7162),l=i(14889),u=i(36297),c=(0,n.defer)((()=>(0,o.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,a.gt0)(await t.size())&&(0,a.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await s.default.get(e.url,{timeout:l.ShortCommandTimeoutMs,...e.config}),n=r.data;u.HttpStatusIs.success(r.status)||c().throw("Failed",{url:e.url,response:r});const o=e.preCacheTransform?.(n)??n;return c().info("Fetch success. Caching",{args:e,json:o,cache:t}),await t.writeJson_(o),{data:o,updatedAt:Date.now(),fromCache:!1}}},83769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAjaxRequest=t.isHttpsRequest=t.parseForwarded=void 0;const r=i(39938),s=i(39784),n=i(91464),a=i(43414);function o(e){if((0,r.blank)(e))return{};let t=(0,s.toA)(e).join(";").trim().replace(/^[,;]/,"").replace(/[,;]$/,"");const i={};for(;t.length>0;){const e=t.indexOf("=");if(e<0)break;const r=(0,n.stripQuotes)(t.slice(0,e).trim().toLowerCase());if(t=t.slice(e+1).trim(),/^["']/.test(t)){const e=/['"]\s*(?:[;,]|$)/.exec(t.slice(1))?.index;if(null==e)break;const s=(0,n.stripQuotes)(t.slice(0,e+2).trim());i[r]=s,console.log("quoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+3).trim()}else{const e=/[;,]|$/.exec(t)?.index;if(null==e)break;const s=t.slice(0,e).trim();i[r]=s,console.log("unquoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+2).trim()}}return i}function l(e){return(0,r.blank)(e)||function(e){return Array.isArray(e)&&0===e.length}(e)?void 0:(0,s.toA)(e).join(";")}t.parseForwarded=o,t.isHttpsRequest=function(e){return null!=e&&"false"!==a.Settings.trustProxy.valueOrDefault&&((0,n.equalsIgnoreCase)("https",o(e.forwarded).proto??l(e["x-forwarded-protocol"])??l(e["x-url-scheme"]))||"on"===l(e["front-end-https"])||"on"===l(e["x-forwarded-ssl"]))},t.isAjaxRequest=function(e){return"application/json"===e?.["content-type"]}},36297:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(75556);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},22356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(11254),s=i(11944),n=i(39938),a=i(49049),o=i(19209);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(4866),s=i(11944),n=i(75556),a=i(48652),o=i(18501),l=i(72612),u=i(43414),c=i(61473),d=i(3874),h=i(19209),f=i(22356);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},3331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(49411),s=i(4866),n=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(39938),s=i(1429),n=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(70612)),n=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},11053:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(70612)),h=i(88491),f=i(43383),m=i(66776),p=i(75556),g=i(4866),y=i(7162),v=i(19658),w=i(28807),b=i(91641),S=i(53525),P=i(60346),M=i(51053),_=i(43414),T=i(75153),E=i(59387),D=(0,g.lazy)((()=>(0,y.mkLogger)("work.CpuUsage"))),k=(0,g.lazy)((()=>{D().warn("Current system load is too high to schedule more work",{currentBusyPct:x.instance().busyPct(),max:_.Settings.cpuBusyPercent.valueOrDefault})}),(v.isTest?15:60)*h.secondMs);t.isTooBusy=function(){const e=x.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(1.2*_.Settings.cpuBusyPercent.valueOrDefault));return(0,p.gte)(e,t)?(k(),!0):(k.unset(),!1)};class x extends w.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,E.singleThreadMode)()?60:M.isWin?20:10)*h.secondMs,rank:b.EndableRanks.first}),r.add(this),s.set(this,new P.Average(5)),n.set(this,new C),(0,p.mapFinite)(F(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??F()}}t.CpuUsage=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,F());const e=new C;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},x.instance=(0,f.defer)((()=>new x));class C{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?Math.round(t/r*100):void D().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+S.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function F(){return M.isWin?void 0:Math.ceil(d.default.loadavg()[0]/(0,T.cpuInfo)().length*100)}},21003:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(70612)),n=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const r=i(79015);let s=!1;function n(){s&&(s=!1,(0,r.ee)().emit("clearCache"),(0,r.ee)().emit("resume"))}t.isPaused=function(){return s},t.pause=function(e=!0){!1===e?n():s||(s=!0,(0,r.ee)().emit("pause"))},t.resume=n},59387:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(4866),s=i(88491),n=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,n.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),s.minuteMs);function b(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=b,t.targetCpuLoadPct=S,t.singleThreadMode=function(){return Math.round(S()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,r.lazy)((function(){const e=Math.max(1,Math.floor(S()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,y().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,r.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(5712),s=i(92332),n=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},84213:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(5712),o=i(79378),l=i(4866),u=i(7162),c=i(79015),d=i(51081),h=i(24409),f=i(11944),m=i(16475),p=i(87748),g=i(75556),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=v,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},29144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=t.workerMethodTimeouts=void 0;const r=i(4866),s=i(92585),n=i(61570),a=i(20636),o=i(12374),l=i(7162),u=i(55568),c=i(4691),d=i(49379),h=i(84571),f=i(43414),m=i(59387),p=i(98023),g=i(84213),y=i(48392),v=i(48011),w=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let b=0;const S=[[v.WorkRequestMethods.buildAssetPreviews_,f.Settings.taskTimeoutMs.valueOrDefault]];async function P(e,...i){let r=(await(0,y.WorkerCluster)()).t;if(r.ended){if((0,c.ending)())return w().warn("onChild(): cluster is ended, running task myself",{method:e,args:i}),v.WorkerFunctions[e](...i);w().warn("onChild(): cluster ended unexpectedly. Restarting.",{method:e,args:i}),r=(await y.WorkerCluster.refresh()).t}const n=(0,t.workerMethodTimeouts)().get(e)??(0,h.statTimeoutMs)(),o={id:b++,method:e,args:i};return(0,s.retryOnReject_)((async()=>{const e=new g.RequestTask(o),t=r.enqueueTask(e);return(0,a.thenOrOnTimeout)(t,n/3,(()=>{w().warn("soft timeout servicing work request",{request:o,timeoutMs:n}),(0,p.onTimeout)()})),(0,a.thenOrTimeoutError)(t,n)}),{maxRetries:f.Settings.maxRetries.valueOrDefault,timeoutMs:n,retryDelay:f.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,d.isRetriableError)(e)})}function M(){for(const e of(0,n.values)(v.WorkerFunctions))e.setShim(void 0)}t.workerMethodTimeouts=(0,r.lazy)((()=>new Map(S))),t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,m.singleThreadMode)()||(0,u.isWorkerService)())w().warn("in single-threaded mode"),M(),await((await y.WorkerCluster.prior())?.end());else for(const[e,t]of(0,n.entries)(v.WorkerFunctions))t.setShim((t=>P(e,t)))},t.clearShims=M},48011:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const r=i(75556),s=i(61570),n=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,n.strEnum)(...(0,s.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,r.isNumber)(e.id)}},48392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(5712),s=i(13056),n=i(4866),a=i(7162),o=i(38307),l=i(91641),u=i(69317),c=i(95237),d=i(53525),h=i(51081),f=i(24409),m=i(29663),p=i(59387),g=i(88491),y=i(87748),v=i(75556),w=i(2934),b=i(82798),S=i(24905),P=i(94845),M=i(43414),_=i(75153),T=i(941),E=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.WorkerCluster.prior())?.t.closeChildProcesses()},t.WorkerCluster=(0,n.lazy)((async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return E().throw("Could not find worker.js");E().info("worker.js found at "+e);const t={id:-1,method:"ping",args:[{}]},i=new r.BatchCluster({processFactory:async()=>(E().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,T.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,P.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:S.ChildServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,_.cpuCount)(),e??(0,p.maxCpus)());return E().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}))},941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(10347),s=i(43414),n=i(32421),a=i(38625),o=i(61570);t.workerEnv=async function(){const e={};for(const t of(0,o.values)(s.Settings))t.hasValue()&&!(0,a.isTrue)(t.opts.transient)&&t.addToEnvMaybe(e);return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},45766:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(97742)),n=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(59694),s=i(39938),n=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(11944),s=i(14439),n=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(47025);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},13783:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(88012),s=i(11944),n=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(43947),s=i(75556),n=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(66776),s=i(90957),n=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(11944),s=i(39938),n=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},81003:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38625),s=i(83965);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s}},43947:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(88491),s=i(1894),n=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},57743:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(75556),s=i(33714),n=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},38360:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExampleDomain=void 0;const r=i(11944),s=i(44726),n=["example.com","example.net","example.org","example.edu",".example",".local"].map((e=>(0,s.stripPrefix)(e,".").split(".")));t.isExampleDomain=function(e){const t=e.toLowerCase().split(".");return n.some((e=>(0,r.arrayEndsWith)(t,e)))}},75117:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEmail=t.isEmailMaybe=void 0;const r=i(39938),s=i(38360),n=i(82798);t.isEmailMaybe=function(e){return null!=o(e)};const a=/^(?.+)@(?.[^@\n\r.\u2028\u2029]*\..+)$/;function o(e){const t=a.exec((0,n.toS)(e).trim());if(null==t?.groups)return;const{local:i,domain:o}=t.groups;return(0,r.blank)(i)||(0,r.blank)(o)||(0,s.isExampleDomain)(o)?void 0:{local:i,domain:o}}t.parseEmail=o},24603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const r=i(85120),s=i(47025);function n(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,s.isFunction)(e)&&(0,s.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,r.deepEql)(e,t,{comparator:u})},t.dateComparator=n,t.functionComparator=a;const o=[n,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=l.get(i);if(null!=r)return r(e,t)??null}for(const i of o){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(11944),s=i(39938),n=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(39784);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(11944),s=i(88491),n=i(66776),a=i(75556),o=i(17078),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(11944);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},77125:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(39938),s=i(38625),n=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(84253);t.ReducerNames=(0,r.strEnum)("fit","sq")},97042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(84253);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(11944),s=i(24603),n=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},66776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(90957),s=i(82798);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(11944),s=i(59694),n=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=s.length;(0,r.filterInPlace)(s,(t=>e(i,t))),t=t||n!==s.length,0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const r=i(59694),s=i(39938),n=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,s){return!(null==s||!l(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,s.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function b(e){return l(e)&&e>0}function S(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return m(t-r,t+r,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=b,t.firstGt0=function(...e){for(const t of e){if(b(t))return t;const e=v(t);if(b(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return b(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,n.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return h(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?_(e/r)*r:_(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!b(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,b(t)?_(100*(b(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(11944),s=i(59694),n=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},98510:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},33912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(75556),s=i(23175),n=i(82798);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},65113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(75556),s=i(82798),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},71756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(39938),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(11944),s=i(82798),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(39784);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},46234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(84253);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(11944),s=i(75556);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},33714:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(75556);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},61715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(84253);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(84253);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(61570),s=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(11944),s=i(37609),n=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const r=i(88491),s=i(61570),n=i(90957),a=i(21669);async function o(e,i,r=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(n,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,n(t.Timeout))}),i);try{r&&(0,s.maybeCall)(l,"unref");const t=await e;o&&(o=!1,n(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,s=!0){const n=await o(e,i,s);if(n===t.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(i)+")");return n}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,r=!0){const s=i-Date.now();return s<=0?t.Timeout:o(e,s,r)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return l(e,s,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:r,unref:s=!0}){const a=await o(e,i,s);return a===t.Timeout?(0,n.tot)(r):a}},31869:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ThumbFits=void 0;const r=i(84253);t.ThumbFits=(0,r.strEnum)("aspect","square")},90957:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(47025);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(11944),s=i(39938),n=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(39938),s=i(11448),n=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(11448),s=i(82798);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},24760:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeQuote=t.AssetQueryOrderByColumns=void 0;const r=i(84253),s=i(82798);t.AssetQueryOrderByColumns=(0,r.strEnum)("capturedAt","updatedAt"),t.maybeQuote=function(e){return null!=(e=(0,s.toS)(e).trim()).match(/\s/)?`"${e}"`:e}},88012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(66776),s=i(75556);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},42313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(84253);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},86768:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkReplace=t.XLocationReplace=t.mkRedirect=t.XLocationRedirect=void 0,t.XLocationRedirect="X-Location-Redirect",t.mkRedirect=function(e,i){return{[t.XLocationRedirect]:e,toast:i}},t.XLocationReplace="X-Location-Replace",t.mkReplace=function(e,i){return{[t.XLocationReplace]:e,toast:i}}},23418:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isServerToast=t.DismissAnchor=t.isToastPlusOnly=void 0;const r=i(39938);t.isToastPlusOnly=function(e){return!0===e?.toastPlusOnly},t.DismissAnchor="#dismiss",t.isServerToast=function(e){return(0,r.notBlank)(e?.text)}},35666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(84253);t.S=(0,r.strEnum)("plus","lite")},11254:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(59694),s=i(39938),n=i(87748),a=i(75556),o=i(84253),l=i(44726),u=i(82669);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},73491:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPath=void 0,t.ApiProgressPath="/api/progress"},48652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(11944),s=i(11448),n=i(75556),a=i(33912),o=i(82669);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},22840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const r=i(20810),s=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(11944),s=i(22840),n=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},82798:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(87748);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},17146:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=void 0;const r=i(4866),s=i(7162),n=i(92661),a=i(55568),o=i(46852),l=i(61253),u=i(82341),c=i(87489),d=i(27522),h=i(25015),f=i(14980),m=i(95694),p=i(98250),g=i(75123),y=i(76333),v=i(49441),w=i(84235),b=i(43414),S=i(11944),P=i(88491),M=i(75556),_=i(49374),T=i(47707),E=i(94332),D=i(63216),k=(0,r.lazy)((()=>(0,s.mkLogger)("Cleanup")));t.cleanup_=async function(){const e=_.Library.instance();null==e?k().info("No library to vacuum."):(k().info("Running tag and search maintenance..."),await(0,D.forceRunTagMaintenance)(),k().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,a.isDbJanitorService)()&&(k().info("Running database maintenance..."),await e.runDbBackup())),k().info("Cleaning child processes..."),await(n.Pids.instance()?.killOldProcs()),k().info("Cleaning stale stat db directories..."),await(0,T.vacuumStatDbDirs)(),k().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({name:"fileCleanup",arr:z(),f:e=>e.cleanup()})};const x=(0,r.lazy)((()=>d.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:v.imageCacheDir_,staleMs:b.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(v.ImageCacheName)}))),C=(0,r.lazy)((()=>d.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>p.PosixFile.for((0,g.readdirCacheDir)()),staleMs:b.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ReadDirCacheName)}))),F=(0,r.lazy)((()=>d.FileCleanup.for({name:"sharedStateFileCleanup",rootNativePath:()=>p.PosixFile.forMaybe(b.Settings.sharedStateDir.valueOrDefault),staleMs:P.hourMs,isPrunable:c.isSharedStateFileOrDir}))),I=(0,r.lazy)((()=>d.FileCleanup.for({name:"previewWipCleanup",rootNativePath:u.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)}))),A=(0,r.lazy)((()=>d.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:f.defaultFsAdvisoryLockDir,staleMs:P.hourMs,isPrunable:m.isPsLockFileOrDir}))),O=(0,r.lazy)((()=>d.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,M.gt0)(b.Settings.syncReportRetentionCount.valueOrDefault)?(0,u.librarySyncReportsDir)():void 0,staleMs:P.hourMs,isPrunable:e=>(0,y.isWip)(e)||(0,h.isCsvExt)(e)})));function L(e){return(0,m.isPsLockFileOrDir)(e)||(0,y.isWip)(e)||(0,l.isSqliteFile)(e)}const R=(0,r.lazy)((()=>d.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:L}))),N=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,E.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:b.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:L})));async function B(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const j=(0,r.lazy)((()=>d.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:B,staleMs:P.hourMs,minRetained:1,isPrunable:L})));function z(){return(0,S.compact)([x(),C(),F(),I(),A(),(0,w.LogDirCleanup)(),O(),R(),N(),j()])}t.fileCleanups=z,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{(0,n.ProcCleaner)();for(const e of z())e.scheduleInterval()}))},64303:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceRebuildLibrary=void 0;const r=i(93813),s=i(30690),n=i(89452),a=i(36310);t.forceRebuildLibrary=function(){s.Asset.dbl.runf((e=>e.update({version:0}))),n.AssetFile.dbl.runf((e=>e.update({version:0}))),a.Operation.dbl.runf((e=>e.where({name:a.OperationNames.enqueueAssetFileUpdates,version:r.AssetFileVersion}).orWhere({name:a.OperationNames.enqueueAssetUpdates,version:r.AssetVersion}).delete()))}},49374:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(36079),u=i(91641),c=i(95557),d=i(4691),h=i(2126),f=i(62936),m=i(82341),p=i(53525),g=i(79141),y=i(95741),v=i(98250),w=i(79403),b=i(49441),S=i(19371),P=i(4866),M=i(55568),_=i(43414),T=i(82041),E=i(46573),D=i(53719),k=i(59387),x=i(39938),C=i(38625),F=i(88491),I=i(6314),A=i(61570),O=i(51662),L=i(94332),R=i(89749),N=i(47707),B=i(97840);class j extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new I.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted({aborted:this.ended}),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await this.statsDbDir_(),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted({aborted:this.ended});const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted({aborted:this.ended}),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted({aborted:this.ended}),(0,M.isStatsDbService)()&&await this.statsDb(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.statsDbDir_=(0,P.lazy)((()=>(0,N.statsDbDir_)())),this.previews=(0,P.lazy)((()=>(0,A.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new B.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.statsDb=(0,P.lazy)((async()=>(0,R.statsDbJanitor)(await this.statsDbDir_()))),this.statsDbFile=(0,P.lazy)((()=>this.statsDb().then((e=>e.dbFile)))),this.onEnd=(0,P.lazy)((async()=>{for(const{ea:e,t}of[{ea:this.statsDb.clear(),t:(0,D.commandTimeoutMs)()},{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup(){return(await this.dbModelJanitor())?.backup_()}}t.Library=j,r=j,n=new WeakMap,s={value:void 0}},37831:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveLibrarySettings=t.importSettings=t.librarySettings=void 0;const r=i(7162),s=i(38307),n=i(82341),a=i(10408),o=i(98250),l=i(43414),u=i(82041),c=i(98024),d=i(39938),h=i(24603),f=i(11448),m=i(82798),p=i(9075),g=(0,r.mkLogger)("LibrarySettings");function y(e={}){return g.tap({msg:"librarySettings",level:"info",result:{scanAllDrives:l.Settings.scanAllDrives.valueOrDefault,scanPath:l.Settings.scanPaths.values,copyAssets:l.Settings.copyAssetsToLibrary.valueOrDefault,autoUpdateCheck:l.Settings.autoUpdateCheck.value,allowUserAgent:l.Settings.allowUserAgent.value,reportErrors:l.Settings.reportErrors.value,...e}})}function v(e){l.Settings.scanAllDrives.setValueIfDefined(e.scanAllDrives),l.Settings.scanPaths.setValueIfDefined(e.scanPath),l.Settings.copyAssetsToLibrary.setValueIfDefined(e.copyAssets),l.Settings.autoUpdateCheck.setValueIfDefined(e.autoUpdateCheck),l.Settings.allowUserAgent.setValueIfDefined(e.allowUserAgent),l.Settings.reportErrors.setValueIfDefined(e.reportErrors)}t.librarySettings=y,t.importSettings=v,t.saveLibrarySettings=async function(e,t){const i=o.PosixFile.forMaybe((0,m.toS)(e).trim())?.resolve(),r=y(),w=l.Settings.libraryDir.valueOrDefault,b=i??o.PosixFile.forMaybe(w);let S=Promise.resolve();const P=(0,f.lazy)((()=>{S=S.then((async()=>{try{v(r),l.Settings.libraryDir.value=w,await(0,u.writeSystemSettings_)(),(0,d.blank)(w)||await(0,u.writeLibrarySettings_)(w),await(0,p.restartLibrary_)()}catch(e){g.warn("Failed to roll back to prior settings",{priorSettings:r,priorLibraryDirValue:w,error:e})}}))}));if(null==b)return{error:"Please choose a directory for your library.",ready:S};const M=b?.nativePath!==w;if(M){try{await(0,n.setupLibraryDirs_)(b)}catch(e){return{error:"Failed to set up "+b+". Please choose a different directory for your library. "+(0,a.errorToS)(e)}}g.info("Library directory changed, asking sync to shut down",{prior:w,new:i?.nativePath}),s.StdoutWrite.shutdownSync()}try{v(t);const e=!(0,h.eql)(r,y());if(null==await(0,u.writeLibrarySettings_)(b.nativePath))return P(),{error:"Cannot write to "+b.nativePath+". Please choose a different directory for your library.",ready:S};l.Settings.libraryDir.value=b.nativePath;try{await(0,u.writeSystemSettings_)()}catch(e){return P(),g.warn("Failed to write system settings",e),{error:"Couldn't write your system settings to "+(0,c.systemSettingsFile)()+": "+(0,a.errorToS)(e),ready:S}}return g.info("saveLibrarySettings()",{libraryDirChanged:M,librarySettingsChanged:e,settings:t,priorSettings:r,currentSettings:y()}),(M||e)&&(S=S.then((()=>(0,p.restartLibrary_)({readSettings:!1})))),{msg:"Saved",ready:S}}catch(e){return P(),g.error("Failed to save settings",{error:e}),{error:"Failed to save settings: "+(0,a.errorToS)(e),ready:S}}}},9075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartLibrary_=void 0;const r=i(4866),s=i(7162),n=i(55568),a=i(38307),o=i(79015),l=i(79403),u=i(43414),c=i(82041),d=i(49374),h=(0,r.lazy)((()=>(0,s.mkLogger)("library.RestartLibrary")));t.restartLibrary_=async function(e){(0,n.isWebService)()&&a.StdoutWrite.shutdownSync(),(e?.readSettings??1)&&await c.readSettings.refresh();let t=Promise.resolve();h().warn("Shutting down prior library...");try{t=d.Library.endPriorInstance()}catch(e){h().warn("ending prior library failed:",{error:e})}(0,o.ee)().emit("clearCache"),u.Settings.libraryDir.broadcastChange(),l.HealthCheck.reset();const i=d.Library.instance();return t=t.then((()=>i?.ready)),(0,n.isWebService)()&&(t=t.then((async()=>{const e=await l.HealthCheck.awaitSettled();"ready"===e.state?a.StdoutWrite.restartSync():h().error("Restarted library, but health check summary was not ready",{summary:e})}))),{ready:t}}},27242:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(19658),s=i(20902),n=i(94845),a=i(43414);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||r.isProd&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},27579:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(9856)),l=a(i(70612)),u=a(i(97742)),c=i(4866),d=i(92507),h=i(7162),f=i(68114),m=i(19658),p=i(55463),g=i(55568),y=i(45113),v=i(91464),w=i(42041),b=i(91641),S=i(95557),P=i(4691),M=i(52289),_=i(10408),T=i(27519),E=i(49379),D=i(17875),k=i(79015),x=i(12737),C=i(49857),F=i(7157),I=i(85352),A=i(9483),O=i(15203),L=i(51053),R=i(11944),N=i(39938),B=i(88491),j=i(43947),z=i(87748),V=i(66776),W=i(17078),U=i(39784),q=i(82798),H=i(27242),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:m.nodeEnv,maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await Z(e);return await(T.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(X))))}function X(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*I.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=X,t.annotateEvent=Z,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[A.LogLevels.fatal,"fatal"],[A.LogLevels.error,"error"],[A.LogLevels.warn,"warning"],[A.LogLevels.info,"info"],[A.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},20990:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},g=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const y=g(i(35001)),v=g(i(97742)),w=i(4866),b=i(7162),S=i(33148),P=i(55568),M=i(25516),_=i(38307),T=i(42041),E=i(95557),D=i(4691),k=i(2126),x=i(7383),C=i(70259),F=i(24905),I=i(44731),A=i(20902),O=i(10408),L=i(53525),R=i(49379),N=i(17875),B=i(79141),j=i(79015),z=i(94329),V=i(91290),W=i(90524),U=i(4657),q=i(27644),H=i(43414),G=i(95699),$=i(82041),J=i(67220),K=i(59387),Y=i(39938),X=i(88491),Z=i(43947),Q=i(6314),ee=i(66776),te=i(50530),ie=i(82798),re=i(27579);t.setupEventHandlers=(0,w.lazy)((()=>{x.PromiseTimer.instance(),(0,j.ee)().on("resume",(()=>(0,J.resume)())),(0,j.ee)().on("pause",(()=>(0,J.pause)())),(0,j.ee)().on("exit",(()=>(0,k.exit)({reason:"exit() event",status:0})))}));class se extends E.EndableWrapper{constructor(e){super(e.name,(()=>m(this,r,"m",l).call(this))),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,new Q.Latch),a.set(this,!1),o.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup()",(()=>m(this,r,"m",u).call(this))))),d.set(this,(0,w.lazy)((()=>{const e=v.default.stdin.pipe(new z.LineReader);return e.on("data",(e=>m(this,r,"m",f).call(this,(0,ie.toS)(e)))),e}))),(0,G.setSettingsDefaults)(),(0,M.setServiceName)(this.name),p(this,s,(0,b.mkLogger)("Service("+this.name+")"),"f"),m(this,r,"m",h).call(this),this.promises=new C.Promises(this.name,K.maxConcurrentImports),this.promises.push("Service.setup()",(()=>this.setup_()))}get name(){return super.name}get ready(){return m(this,n,"f").promise}get isReady(){return m(this,n,"f").isResolved()}setInputHandler(e,t){m(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,d=new WeakMap,r=new WeakSet,l=async function(){await this.promises.awaitAll()},u=async function(){try{(0,Y.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new B.WrappedError(e,{fatal:!0})})),(0,Y.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new B.WrappedError(e)}),5*X.secondMs)})),(0,S.setProcessTitle)(),(0,P.isMainService)()&&await(0,q.mergeUserDataDirs_)(),await(0,$.readSettings)(),await m(this,r,"m",c).call(this),U.setupLogger.refresh(),(0,t.setupEventHandlers)(),m(this,d,"f").call(this),await(0,I.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,J.pause)(),(0,D.ending)()?m(this,n,"f").reject():m(this,n,"f").resolve()}catch(e){console.error((0,O.errorToS)(e)),m(this,n,"f").reject((0,te.toErr)(e)),(0,k.exit)({reason:(0,R.addErrorFlags)(this.name+" setup failed: "+(0,O.errorToS)(e),L.FatalErrorFlag),status:14})}},c=async function(){(0,P.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),v.default.on("unhandledRejection",(e=>(0,ee.map)(e,(e=>(0,N.onError)("unhandledRejection",e))))),v.default.on("uncaughtException",(e=>(0,ee.map)(e,(e=>(0,N.onError)("uncaughtException",e))))),v.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),v.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),v.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),y.default.isWorker&&v.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,re.installSentry)(this)},h=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(F.ChildServiceExitCommand,(()=>(0,Z.later)((()=>(0,k.exit)({reason:F.ChildServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(W.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,V.getStatusSummary)({refresh:!0}))))},f=function(e){return m(this,s,"f").debug("onLine()",{line:e,ending:m(this,a,"f")||(0,D.ending)()}),this.promises.serial("Service.onLine()",(async()=>{if(await this.setup_(),e.startsWith("--")){const t=e.split(" ",1)[0],i=m(this,o,"f").get(t);null==i?(m(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...m(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else try{await(0,ee.map)(this.opts.stdinReceiver,(t=>t(e)))}catch(t){m(this,s,"f").error("onLine(): failed to process",{line:e,error:t})}}))}},59960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdown=void 0;const r=i(4866),s=i(7162),n=i(38307),a=i(4691),o=i(2126),l=i(56958),u=i(11353);let c="unspecified";t.shutdown=function(e){return(0,s.mkLogger)("Shutdown").warn("shutdown()",{reason:e}),c=e,d()};const d=(0,r.lazy)((async()=>{n.StdoutWrite.shutdown(),(0,l.broadcastExit)(),(0,u.setUnrefTimeout)((()=>(0,a.ending)()?void 0:(0,o.exit)({reason:c,status:0})),3e3)}))},47707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmStatDbDirs=t.vacuumStatDbDirs=t.statsDbDir_=t.statDbDirs=t.CacheDirPrefix=void 0;const r=i(4866),s=i(7162),n=i(93813),a=i(29731),o=i(76915),l=i(1629),u=i(98250),c=i(43586),d=i(47987),h=i(6231),f=i(6667),m=i(43414),p=i(82041),g=i(88491),y=i(87748),v=(0,r.lazy)((()=>(0,s.mkLogger)("library.StatsDbDir")));function w(){return u.PosixFile.for((0,l.cacheDir_)()).clear().children((e=>e.name.startsWith(t.CacheDirPrefix)))}async function b(e=!0){if(!(0,p.libraryHasSettings)())return;const i={AssetVersion:n.AssetVersion,AssetFileVersion:n.AssetFileVersion,LibraryUID:await((0,c.LibraryUIDStore)()?.readUid_()),SystemUID:await((0,c.SystemUIDStore)()?.readUid_())},r=(0,a.shortStringSha)((0,y.stringify)(i),10,h.TokenRadix),s=u.PosixFile.for((0,l.cacheDir_)()).join(t.CacheDirPrefix+r);return e?(await(0,d.writeTextfile_)(s.join("README.txt").nativePath,"","This folder holds state for library synchronization of","",m.Settings.libraryDir.value,"","Don't edit the contents of this directory while PhotoStructure is running.","","If you have any questions, please visit https://forum.photostructure.com","",(0,y.stringify)(i,void 0,2)),v().info("Set up statsDbDir dir "+s),s):s}async function S(e){!0===e.name.startsWith(t.CacheDirPrefix)?await e.rmrf():v().warn("rmStatDbDir(): refusing to rm "+e)}t.CacheDirPrefix="sync-state-",t.statDbDirs=w,t.statsDbDir_=b,t.vacuumStatDbDirs=async function(){const e=await b();for(const t of await w()??[]){if(t.eql(e))continue;const i=(0,f.max)(await Promise.all([t.join("README.txt").mtimeMs(),t.join(o.SqliteBase).mtimeMs()]));(null==i||i(0,l.mkLogger)("library.SuggestedLibraryDir")));class I{static async for(e,t){if((0,k.blank)(e))return;const i=await(0,T.bestVolumeForPath)(e,t);if(null==i)return void F().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,m.isLibraryDir)(e);return new I(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=_.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=_.Settings.minDiskFreeGb.valueOrDefault*C.GB){if(this.isLibrary)return;const t=await(0,P.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,b.containsHiddenPathname)(this.nativePath))return F().tap({...i,result:"contains hidden path"});{const e=await(0,w.whyExcludedDirectoryRecursive)(v.BaseFile.for(this.nativePath));if(null!=e)return F().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,y.canRWXFirstExistingAncestor)(this.nativePath)?(0,x.gt0)(e)&&this.availableBytesnew I(e,!1,{mountpoint:"/test",available:C.GB})))});const l=[],d=[],y=await i??await(0,T.volumes)();if(null==y||(0,E.isEmpty)(y))return F().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await I.for(t,y);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(F().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(_.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,p.picturesDir)());const w=[n.default.cwd(),...await(0,S.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,S.childDirectories_)((0,f.homeDir)())),(0,E.filterInPlace)(w,(e=>(0,b.isNotHiddenPosixPath)(e)));for(const e of w)await(0,m.isLibraryDir)(e)&&(F().info("current working dir is a library",e),await v(e));function P(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(F().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,f.homeDir)(),(0,a.AppName)())),await(0,h.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:y,f:e=>async function(e){try{if(await(0,m.isLibraryDir)(e.mountpoint))return F().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,S.childDirectories_)(e.mountpoint)){if(P())break;if(await(0,m.isLibraryDir)(t))F().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,S.childDirectories_)(t)){if(P())break;await(0,m.isLibraryDir)(i)&&(F().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());F().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){F().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),F().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const k=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(k.length>=t)break;k.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(F().debug("adding new path",e),k.push(e))}return(0,E.uniqBy)((0,D.sortBy)(k,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=I,t.suggestedLibraryDirs=(0,o.lazy)((()=>A())),t._suggestedLibraryDirs=A},98505:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(45161),s=i(35796),n=i(54883),a=i(79403),o=i(69060),l=i(95976),u=i(55463),c=i(33407),d=i(55568),h=i(43414),f=i(82041),m=i(45113),p=i(24586),g=i(42041),y=i(11053),v=i(59387),w=i(11944),b=i(39938),S=i(38625),P=i(19067),M=i(66776),_=i(75556),T=i(26588),E=i(44726),D=i(17078),k=i(30690),x=i(89452),C=i(50725);async function F(){if(null==k.Asset.db())return;const e=[];e.push((0,D.plurMetric)(k.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,D.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,D.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const I={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:I[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,M.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,M.map)(y.CpuUsage.instance().busyPct(),(e=>(0,_.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,_.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},51731:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(43414),s=i(38625);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,s.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},92045:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(55568),s=i(85297),n=i(43414),a=i(38625);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},18290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(4866),s=i(92507),n=i(70283),a=i(91464),o=i(46175),l=i(79015),u=i(43414),c=i(65642),d=i(96593),h=i(11944),f=i(66776),m=i(75556),p=i(11254),g=i(82798),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},52465:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(7162),s=i(43414),n=i(61473),a=i(11254),o=i(11944),l=i(39938),u=i(43383);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},18130:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(13779),d=i(4866),h=i(55568),f=i(91641),m=i(95557),p=i(4691),g=i(57510),y=i(21808),v=i(3293),w=i(5853),b=i(76851),S=i(92345),P=i(62936),M=i(79141),_=i(79403),T=i(43414),E=i(88491),D=i(75556),k=i(61570),x=i(23175),C=i(6628),F=i(72537),I=i(51603);class A extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=E.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),T.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*E.secondMs),this.migrate_=(0,d.lazy)((async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{(0,F.verifyDb_)(this.db)}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||T.Settings.dbForceRecover.valueOrDefault)&&(_.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new C.Migration(this.schema,this.db,t),s=await r.apply_();return this.logger.tap({msg:"migrate_",result:{appliedMigrations:s,migration:r,repaired:e}})})),this.tableInfo_=(0,d.lazy)((()=>(0,I.localTableInfo)(this.db)))}toJSON(){return(0,k.pick)(this,"schema","dbFile")}get open(){return null!=l(this,n,"f")&&l(this,n,"f").open}get inTransaction(){return this.open&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(!this.open){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,w.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===T.Settings.dbAutoVacuumMode.valueOrDefault&&(0,D.gt0)(T.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%T.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&l(this,n,"f")?.pragma("incremental_vacuum"),l(this,n,"f")}verify_(){return(0,F.verifyDb_)(this.db)}assertHeartbeat_(){const e=(0,x.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}closeDb(){try{!0===l(this,n,"f")?.open&&(this.logger.info("closing db",l(this,n,"f")),l(this,n,"f")?.close())}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>(0,F.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),this.closeDb(),await(0,F.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,P.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,S.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,g.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,y.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=A,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,b.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,D.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},51662:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(37410),d=i(7162),h=i(28807),f=i(91641),m=i(95557),p=i(4691),g=i(7383),y=i(57510),v=i(21808),w=i(61253),b=i(9816),S=i(19653),P=i(43414),M=i(88491),_=i(19067),T=i(41593),E=i(94332),D=i(91894),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends h.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:f.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new m.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),f.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,g.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,y.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:f.EndableRanks.postdb,noopIfContested:!1});await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,w.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),this.db.closeDb()},o=function(){return this.ended||(0,p.ending)()||(0,c.isSuspended)()||(0,b.isUpdateReadyToInstall)()}},3382:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelRepair=void 0;const r=i(4866),s=i(7162),n=i(55568),a=i(38307),o=i(10408),l=i(53525),u=i(79403),c=i(43414),d=i(53719),h=i(49374),f=i(9075),m=i(91796),p=i(41593),g=i(94332),y=i(91894),v=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelRepair")));t.dbModelRepair=async function(){return{...await async function(){const e=h.Library.instance();if(null==e)throw new Error("No library set."+l.NoLibraryErrorFlag);const t=await e.dbModelJanitor();if(null==t)throw new Error("No library set (missing dbModelJanitor)."+l.NoLibraryErrorFlag);(0,y.clearDbSetupErrors)();const i=await(0,m.dbModelHealthCheck)().refresh();if(v().info("dbModelRepair: health check result: ",i),c.Settings.dbForceRecover.valueOrDefault)u.HealthCheck.addLoadingMsg("PS_DB_FORCE_REPAIR was set. Trying to repair.");else if("ok"!==i.level)u.HealthCheck.addLoadingMsg(`Database health check failed: ${i.msg}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0;else try{return u.HealthCheck.addLoadingMsg("Running maintenance tasks..."),await(0,p.runMaintenanceTasks)({force:!0}),u.HealthCheck.addLoadingMsg("Backing up the library database..."),await t.forceBackup_(),u.HealthCheck.addLoadingMsg("Validating the library database..."),await t.db.verify_(),u.HealthCheck.addLoadingMsg("No repair needed: maintenance tasks, backup, and integrity tests ran without error."),v().tap({msg:"dbModelRepair()",level:"info",result:{noop:!0,op:"validated"}})}catch(e){u.HealthCheck.addLoadingMsg(`Maintenance, backup, or integrity tasks failed: ${(0,o.errorToS)(e)}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0}(0,n.isWebService)()&&a.StdoutWrite.shutdownSync();const r=await e.dbFsLock();if(!await r.acquire_({timeoutMs:2*(0,d.commandTimeoutMs)(),releaseOnFailure:!1}))return v().throw("Failed to acquire exclusive lock on the library database. Shut down other processes before retrying.");try{await(0,g.assertValidDbInfo_)()}catch(e){u.HealthCheck.addLoadingMsg(`Library database setup was invalid: ${(0,o.errorToS)(e)}. Resetting and restarting.`),await(0,g.libraryDbInfoJsonFile)().unlink(),c.Settings.dbForceRecover.envValue=!0}await(0,f.restartLibrary_)();const s=c.Settings.dbForceRecover.valueOrDefault;return c.Settings.dbForceRecover.unset(),v().tap({msg:"dbModelRepair()",level:"info",result:{op:s?"repaired":"restarted",noop:!1}})}(),state:(await u.HealthCheck.rerunSetup()).state}}},94332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(4866),s=i(7162),n=i(24193),a=i(21808),o=i(92345),l=i(62936),u=i(82341),c=i(10408),d=i(53525),h=i(19653),f=i(98250),m=i(95725),p=i(79403),g=i(9483),y=i(43414),v=i(82041),w=i(11944),b=i(39938),S=i(88491),P=i(9069),M=i(18130),_=i(91894),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},78650:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(51498),s=i(4866),n=i(7162),a=i(4691),o=i(7383),l=i(66097),u=i(95976),c=i(43414),d=i(11944),h=i(39938),f=i(1429),m=i(44726),p=i(18273),g=i(66056),y=(0,s.lazy)((()=>(0,n.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,p.knex)()(this.tableName)}prep(e,t=!1){const i=(0,g.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return y().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&y().log((0,u.defaultLogLevel)(),i+"(): "+(0,g.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;y().throw(t,{method:i,...(0,g.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,o.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,m.replaceAll)((0,m.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,g.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,f.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}batched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t)&&!(0,a.ending)())}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}pluckBatched(e){let t;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,l.maxBatchPluckSize)()),pluck:!0,m:"all"}),(0,d.isNotEmpty)(t)&&e.onResults(t)}while((0,d.isNotEmpty)(t))}}},13915:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeSchemaJsonFile_=t.assertValidDbSchema_=t.schemaJsonFile=void 0;const s=r(i(49411)),n=i(13779),a=i(4866),o=i(7162),l=i(98250),u=i(27175),c=i(11944),d=i(51367),h=i(17078),f=i(91796),m=i(51603),p=(0,a.lazy)((()=>(0,o.mkLogger)("db.DbSchemaValid")));function g(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=g,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,m.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await g(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&p().throw("Db is missing "+(0,h.plur)(t.length,"table")+" : "+(0,d.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)p().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&(p().error("Missing columns",{expected:t,actual:e}),p().throw("Db is missing "+(0,h.plur)(i.length,"column")+" from table "+e.tableName+" : "+(0,d.andList)(i.map((e=>e.name)))))}}p().info("Validated schema.")}catch(e){throw(0,f.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return g(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,m.localTableInfo)(t)},{spaces:2})}},91894:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(10408),s=i(39938),n=i(22840);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},85476:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(4866),s=i(7162),n=i(91464),a=i(61473),o=i(11944),l=i(59694),u=i(89253),c=i(75556),d=i(82798),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},18273:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(40514)),n=i(4866),a=i(46852),o=i(66776),l=i(61570);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},6628:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(6005),l=i(4866),u=i(7162),c=i(19658),d=i(42041),h=i(37121),f=i(76851),m=i(42648),p=i(53525),g=i(17875),y=i(79141),v=i(79015),w=i(19653),b=i(98250),S=i(27175),P=i(79403),M=i(11944),_=i(39938),T=i(88491),E=i(43947),D=i(87748),k=i(66776),x=i(8199),C=i(47025),F=i(91894),I=i(12586),A=i(72537);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,I.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:2*T.minuteMs},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=I.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(I.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.debug("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),c.isProd&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeout)(this.applyMigration_(r,i),T.minuteMs,(()=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile();if((0,_.blank)(i))return void this.logger.error("Empty migration: "+e);t&&this.db.pragma("foreign_keys = OFF");for(const t of(0,f.splitBatchSql)(i))try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,A.foreignKeyCheck_)(this.db)}finally{t&&this.db.pragma("foreign_keys = ON")}}},12586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(70283),o=i(1058),l=i(91464),u=i(81108),c=i(80654),d=i(53682),h=i(76387),f=i(68074),m=i(54809),p=i(64455),g=i(70208),y=i(61473),v=i(25116),w=i(11944),b=i(66776),S=i(75556),P=i(98510),M=i(49049),_=i(82798),T=i(54578),E=i(85476),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)},t.isoToPrecisionMs=F,t.Migrations={lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},recount_tag_asset_counts:T.rebuildTagAssetCounts}},72537:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(70403),s=i(4866),n=i(7162),a=i(69317),o=i(57510),l=i(29393),u=i(3293),c=i(94794),d=i(61253),h=i(76851),f=i(53525),m=i(79141),p=i(3955),g=i(98250),y=i(22143),v=i(4416),w=i(43414),b=i(53719),S=i(92585),P=i(88491),M=i(43947),_=i(24603),T=i(87748),E=i(6314),D=i(75556),k=i(26588),x=i(44726),C=i(17078),F=i(39784),I=i(82798),A=i(9069),O=i(70582),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${function(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}(e)}: ${(0,T.stringify)(r)}`)}function N(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function B(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function j(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function z(e){await(0,u.handleDbRetries_)("db.quickCheck",(()=>N(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",(()=>B(e))),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",(()=>j(e)))}function V(e){return(0,O.withDbSync)(e,z,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,A.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=N,t.integrityCheck_=B,t.foreignKeyCheck_=j,t.verifyDb_=z,t.verifyDbFile_=V,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const W=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,I.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,I.toS)(e);W.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;L().info("repairDbFile_(): dump",{len:t}),n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),V(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},66056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(13779),s=i(1058),n=i(91464),a=i(80807),o=i(1429),l=i(87748),u=i(75556),c=i(61570),d=i(47025),h=i(82798);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},51603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(39938),s=i(89253);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},70582:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(5853),s=i(43414),n=i(82798);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return t(a)}finally{a.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const a=(0,r.mkdb_)({nativePath:(0,n.toS)(e),timeoutMs:i});try{return await t(a)}finally{a.close()}}},91796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(42648),s=i(10408),n=i(79403),a=i(82041),o=i(36535),l=i(88491),u=i(43383),c=i(49374),d=i(13915),h=i(91894),f=i(77910),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library databaseโ€ฆ",settings:["libraryDir","forceLocalDbReplica"],ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{if(!(0,a.libraryHasSettings)())return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let e,t,i=!1;try{const s=Date.now();if(i=!1,t=c.Library.instanceRequired(),(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(await t.ready,e=await t.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(e),i=!0,await e.verify_(),await e.vacuum(),f.Heartbeat.assertPing_();const n=await t.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(e.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==e?void 0:"Live db is "+(0,o.tt)(e.dbFile.nativePath),null==t?void 0:"Local replica mode is "+(0,o.tt)(await t.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},39946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(4866),s=i(46747),n=i(82041),a=i(91796),o=i(23134),l=i(53829);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},23134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(13779),s=i(7162),n=i(98250),a=i(23872),o=i(79403),l=i(82041),u=i(11944),c=i(36535),d=i(43383),h=i(71766),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directoriesโ€ฆ",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},53829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(7162),s=i(46852),n=i(79403),a=i(43414),o=i(82041),l=i(47044),u=i(53719),c=i(27127),d=i(46573),h=i(11944),f=i(36535),m=i(43383),p=i(51367),g=i(89253),y=i(61570),v=i(71766),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumesโ€ฆ",settings:["scanAllDrives"],links:[{text:"What's a โ€œvolumeโ€?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" โ†’ "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},30690:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(13779),c=i(4866),d=i(7162),h=i(2023),f=i(93813),m=i(46852),p=i(68074),g=i(53525),y=i(74836),v=i(43414),w=i(96593),b=i(84418),S=i(11944),P=i(59694),M=i(13783),_=i(38625),T=i(9381),E=i(87748),D=i(66776),k=i(75556),x=i(26588),C=i(39784),F=i(49374),I=i(18290),A=i(89452),O=i(14405),L=i(10074),R=i(61331),N=i(13222),B=i(50725),j=i(94358),z=i(1724),V={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class W extends z.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,w.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,_.isTrue)(t.shown)})}const t=L.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new b.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(V):e.andWhere(V)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{blocklistShas:t,unlinkAssetFiles:i});const l=A.AssetFile.dbl.allf((t=>t.select("sha","uri","mountpoint").where({assetId:e})));t&&(0,N.upsertToShaBlockslist)(...l.map((e=>e.sha))),R.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),A.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),L.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&B.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,y.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(R.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),A.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,O.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:B.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,S.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new A.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return B.Tag.ops().all(B.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??R.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:B.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:B.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,S.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,S.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,S.isEmpty)(i)&&(0,S.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&B.Tag.deltaAssetCountAndAncestors(t,-1),(0,S.isEmpty)(i)||R.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,S.isEmpty)(r)||R.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,S.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&B.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,j.coalesceStreams)((0,S.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,P.sortBy)(A.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,_.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof A.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof A.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,E.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();A.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=A.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,_.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,T.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,x.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(A.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new A.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,_.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=W,s=W,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},W.$tableName="Asset",W.$uniqueColumnName="id",W.$booleanFields=["shown","hidden"]},89452:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(49411),o=i(4866),l=i(2023),u=i(93813),c=i(1058),d=i(91464),h=i(75288),f=i(68668),m=i(46852),p=i(65976),g=i(68074),y=i(10408),v=i(53525),w=i(17875),b=i(3955),S=i(98250),P=i(23872),M=i(24948),_=i(31053),T=i(43414),E=i(65642),D=i(27446),k=i(3874),x=i(19209),C=i(25116),F=i(36974),I=i(22356),A=i(11944),O=i(37609),L=i(39938),R=i(38625),N=i(88491),B=i(57743),j=i(24603),z=i(19067),V=i(9381),W=i(66776),U=i(75556),q=i(61570),H=i(8199),G=i(49049),$=i(11254),J=i(49374),K=i(97840),Y=i(30690),X=i(13222),Z=i(50725),Q=i(1724);class ee extends Q.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>x.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{if(!0===(0,X.isShaBlockslisted)(this.sha))return"blocklisted SHA";const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=(e.q??this.query()).where("version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,A.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("uri",i+"%");return t})).orderBy("id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,U.gt0)(e)?ee.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,L.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(ee.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=ee.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=ee.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:ee.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",G.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith(G.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,W.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,U.closeTo)(i.mtime,this.mtime,2*N.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return T.Settings.forceSync.valueOrDefault?"forceSync":null==this.version||this.versione.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=T.Settings.forceSync.valueOrDefault){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,U.gt0)(this.id)&&!t)return this.upsert(),void(this.syncState=M.AssetFileSyncStates.noop);const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),this;if(!1===i){const t=await this.updateFromFile_(e);return this.syncState??(this.syncState=null==t?M.AssetFileSyncStates.skipped:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e){const t=Date.now(),i=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&await this.matchesFile(e))return void i.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void i.info("no-op, "+e+" is missing");const r=await(0,h.mkAssetFile_)(e);return r.uri!==this.uri&&((0,L.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:r.uri}),this.uri=r.uri),(0,q.assignAllFields)(this,(0,q.omit)(r,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,i.elapsed("finished",Date.now()-t,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...ee.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,U.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,L.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,L.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,L.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),E.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,B.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,R.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,A.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===V.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,A.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=x.URI.parse(this.uri),t=(0,W.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=x.URI.parse(this.uri),s=await t.exists();if(null==e||(0,A.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,O.at)((0,O.at)(e,-1)?.tagPath,-1)}(0,j.eql)(e[0]?.tagPath,[$.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===G.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,O.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===$.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===G.PS_LOCAL_FILE_SCHEME){const t=x.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,R.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:(0,W.orElse)(this.rotation,0),fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:te(this.createdAt),updatedAtLocale:te(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function te(e){return(0,W.map)(e,(e=>(0,z.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=ee,r=new WeakSet,s=function(){return(0,L.blank)(this.uri)?"blank uri":(0,L.blank)(this.sha)?"blank sha":(0,U.gt0)(this.width)?(0,U.gt0)(this.height)?(0,U.gt0)(this.capturedAtLocal)?(0,U.gte0)(this.capturedAtPrecisionMs)?T.Settings.useImageHashes.valueOrDefault&&((0,L.blank)(this.meanHash)||(0,L.blank)(this.diffHash)||(0,L.blank)(this.dctHash))?"missing image hashes":this.isVersionUpToDate()?void 0:"outdated version":"missing capturedAtPrecisionMs":"missing capturedAtLocal":"missing height":"missing width"},ee.$tableName="AssetFile",ee.$uniqueColumnName="uri",ee.$booleanFields=["shown"],ee.$transientFields=["nativePath","syncState"]},14405:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(80294),s=i(75556);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},10074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(87748),s=i(2934),n=i(7907);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},63232:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setAssetRotation_=void 0;const r=i(7162),s=i(5685),n=i(87489),a=i(34956),o=i(11944),l=i(43383),u=i(87748),c=i(75556),d=i(33714),h=i(30690),f=(0,l.defer)((()=>new s.LastOneInWins("Asset")));t.setAssetRotation_=async function(e,t,i){if(!(0,c.gt0)(e))throw new Error("invalid asset "+(0,u.stringify)(e));if(!(0,d.isRotation)(t))throw new Error("setRotation("+t+"): invalid rotation "+(0,u.stringify)(t));return f().enqueue(e,(async s=>async function(e,t,i,s){const c=Date.now(),d=(0,r.mkLogger)("setAssetRotation("+(0,u.stringify)({assetId:e,rotation:t})+")"),f=h.Asset.ops().findById(e);if(null==f)return d.throw("Unknown assetId:"+e);const m=(0,l.defer)((()=>{(0,n.submitTask_)("repairAsset",{assetId:e})}));d.throwIfAborted(s);const p=await i.ap(e).smallestFileForReducer("fit");if(null==p)return m(),d.throw("Missing previews for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const g=f.getAssetFiles();if(null==f.getShown())return m(),d.throw("No primary asset file for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const y=[];for(const e of g)try{const i=await e.posixFile();if(null==i||await i.notExists()){d.info("cannot rotate variation: file is missing",{f:i,af:e});continue}if(null==await(0,a.matchAndWriteRotation_)(p,i,t)){d.info("cannot rotate variation: matchRotation() failed",{f:i,af:e});continue}y.push(await e.upsertIfNeeded_(i.clear(),!0))}catch(t){d.warn("failed to update asset file",{af:e,error:t})}return(0,o.compact)(y),(0,o.isNotEmpty)(y)&&await i.apb(e,g,{forceRebuildPreviews:!0}).build_(),d.info("setRotation("+t+"): completed.",{elapsedMs:Date.now()-c,updatedAssetFiles:y}),y}(e,t,i,s.signal)))}},61331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(7907);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},55916:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(4866),s=i(7162),n=i(70283),a=i(11254),o=i(18290),l=i(50725),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},77910:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(53525),s=i(88491),n=i(75556),a=i(1724);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},41593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(4866),s=i(7383),n=i(43414),a=i(88491),o=i(43947),l=i(63216),u=i(55916),c=i(65548);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h()),await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},7907:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(47261),n=i(7162),a=i(19658),o=i(37086),l=i(11944),u=i(38625),c=i(43383),d=i(75556),h=i(61570),f=i(8199),m=i(82798),p=i(18273),g=i(9069),y=i(79563),v=i(5333);class w{constructor(){this.$instanceId=a.isTest?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},9069:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(62936),s=i(82341),n=i(4866),a=i(66776);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},79563:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(7162),s=i(11944),n=i(39938),a=i(38625),o=i(98510),l=i(44726),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},5333:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(13779),m=i(4866),p=i(7162),g=i(91464),y=i(22568),v=i(80807),w=i(53525),b=i(79015),S=i(43414),P=i(11944),M=i(59694),_=i(39938),T=i(24603),E=i(1429),D=i(87748),k=i(66776),x=i(75556),C=i(61570),F=i(39784),I=i(78650),A=i(79563);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,A.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new I.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.open),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){return(0,P.compact)(e.map((e=>this.reloadOne(e))))}upsert(e,t=!1){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const i=this.columnNames(),s=[];for(const n of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=(0,P.compact)(n.map((e=>this.fromJSON(e)))),a=e.map((e=>this.model.pickId(e)));for(const t of e)t.$beforeUpsert();h(this,r,"m",c).call(this,e.map((e=>e.$toDbJSON(i))));for(const[i,r]of(0,f.zip)(e,a)){const e=t?i:this.reloadOne(i)??i;(0,T.eql)(r,this.model.pickId(e))||e.$afterInsert(),e.$afterUpsert(),s.push(e)}}return s}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},36310:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(4691),s=i(4866),n=i(7162),a=i(2023),o=i(39938),l=i(84253),u=i(1724);t.OperationNames=(0,l.strEnum)("rebuildLibrary","forceRestartSync","enqueueAssetFileUpdates","enqueueAssetUpdates","applyNewTagger","applyExcluded","applyDeleted");const c=(0,s.lazy)((()=>(0,n.mkLogger)("model.Operation")));class d extends u.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(d.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return d.getFirstPendingOp(e)??d.ops().insertOne(e)}static getFirstPendingOp(e){return c().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,o.blank)(e?.name)?c().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return c().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce(e,t,i=a.identity){const s=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=s)return void c().debug("applyOnce(): already done",{priorCompleted:s});const n=this.ops().insertOne(e),o=await t(n);return(0,r.ending)()||n.upsert({completedAt:Date.now()}),o}}t.Operation=d,d.$tableName="Operation",d.$uniqueColumnName="id"},65548:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.ProgressRateMs=void 0;const r=i(70612),s=i(97742),n=i(4866),a=i(7162),o=i(53525),l=i(33407),u=i(43414),c=i(59387),d=i(11944),h=i(88491),f=i(87748),m=i(66776),p=i(61570),g=i(2934),y=i(26588),v=i(44726),w=i(39784),b=i(79563),S=i(36310),P=i(33075),M=i(1724),_=(0,n.lazy)((()=>(0,a.mkLogger)("model.Tag")));t.ProgressRateMs=(0,n.lazy)((()=>h.secondMs*((0,l.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:2)));const T=(0,v.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n WHERE createdAt > :minCreatedAt\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n createdAt > :minCreatedAt\n AND CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nWHERE p1.createdAt > :minCreatedAt\nGROUP BY\n p1.uri");function E(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}t.defaultMinCreatedAt=E;class D extends M.TimestampedModel{static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t))),r=P.ProgressMeta.dbl.pluckAllf((e=>e.select("id").whereIn("progressId",i)));P.ProgressMeta.ops().delete(r),D.ops().delete(i)}static minCreatedAt(){const e=S.Operation.getFirstPendingOp({name:S.OperationNames.forceRestartSync});return _().tap({msg:"minCreatedAt",level:"info",result:e?.createdAt??E(),meta:{op:e}})}static times(){const e=this.minCreatedAt();return _().tap({msg:"times()",result:this.dbl.all({sql:T,bindings:{minCreatedAt:e}}),meta:{minCreatedAt:e}})}static async saveSyncState(e){return(0,y.thenCollect)((0,w.toA)(await e.progress()),(e=>("done"===e.state&&null==e.completedAt&&(e.completedAt=Date.now()),null==e.id?_().throw("saveSyncState() returned an unsaved Progress"+o.InternalErrorFlag,e):e.upsert())))}static insertNew(e){const t=(0,m.map)(e.dek,f.stringify);return this.ops().insertOne({...(0,p.omit)(e,"dek"),pid:s.pid,hostname:(0,r.hostname)(),dekJSON:t})}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,d.compactBlanks)((0,g.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,f.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,p.omit)(e,"volume","uri"))}getThisMeta(){return P.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncompleteProgress(){const e=D.minCreatedAt(),t=D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri}).andWhere("createdAt",">",e).orderBy("updatedAt","desc").limit(1)));return null!=t?.completedAt?this.logger().tap({msg:"priorIncompleteProgress(): last Progress was complete",result:void 0,meta:{prior:t}}):this.logger().tap({msg:"priorIncompleteProgress()",result:t})}getPriorIncompleteMeta(){return this.getPriorIncompleteProgress()?.getThisMeta()}getMeta(){const e=this.getThisMeta();if((0,d.isNotEmpty)(e))return e;{const e=this.getPriorIncompleteMeta();return(0,d.isNotEmpty)(e)?(this.logger().info("getMeta(): inheriting prior progress",e),P.ProgressMeta.ops().upsert(e.map((e=>({progressId:this.id,name:e.name,value:e.value}))),!1)):(this.logger().info("getMeta(): no relevant prior progress"),[])}}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),P.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),P.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),P.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,p.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},33075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=void 0;const r=i(84253),s=i(1724);t.ProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync");class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},13222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.installBadShaShim=t.listenForInvalidFiles=t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(4866),s=i(7162),n=i(79015),a=i(98250),o=i(65564),l=i(11944),u=i(39938),c=i(78650),d=i(9069),h=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),f=(0,r.lazy)((()=>new c.DbRequest(d.modelDb,"ShaBlocklist")));function m(e){return null!=(0,d.modelDb)()&&!(0,u.blank)(e)&&h().tap({msg:"isShaBlockslisted",result:null!=f().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}async function p(e){if(null==(0,d.modelDb)())return;const t=await a.PosixFile.for(e).sha();return null==t?void 0:g(t)}function g(...e){if(null==d.modelDb.prior())return;const t=(0,l.uniq)(e).map((e=>({sha:e})));return(0,l.isEmpty)(t)?void 0:f().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,d.modelDb)())return null;const t=m(await a.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=m,t.upsertFileToShaBlockslist=p,t.upsertToShaBlockslist=g,t.listenForInvalidFiles=(0,r.lazy)((()=>{(0,n.ee)().on("invalidFile",p)})),t.installBadShaShim=(0,r.lazy)((()=>{o.isBadSha.setShim(m)}))},50725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(7383),o=i(79015),l=i(4866),u=i(7162),c=i(72755),d=i(70283),h=i(43414),f=i(91464),m=i(61473),p=i(11254),g=i(11944),y=i(39938),v=i(88491),w=i(43947),b=i(24603),S=i(66776),P=i(75556),M=i(8199),_=i(26588),T=i(44726),E=i(39784),D=i(17078),k=i(52465),x=i(18273),C=i(66056),F=i(54578),I=i(30690),A=i(14405),O=i(61331),L=i(21250),R=i(94358),N=i(1724),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:I.Asset.dbl.pluckFirst(I.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.upsert({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static cacheTag(e){return 0===e?.parentId&&this.root.unset(),e}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),r.cacheTag(this.ops().upsertOne(i))}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}$afterUpsert(){r.cacheTag(this)}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return I.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)}));const i=r.ops().all(t);for(const e of i)r.cacheTag(e);return i}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(I.Asset.dbl.all(t).map(A.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return I.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.AssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?I.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(I.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(A.toAssetId))));for(const t of r)t.assetIdI.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(0,S.orElse)(this.id,0),"Asset.id",i)).limit(t))).map(A.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!1,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=I.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));return e.forEach((e=>{e.parentId=void 0,e.ancestors=[],r.cacheTag(e)})),e}),B);const V=(0,l.lazy)((()=>I.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},21250:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(62936),s=i(59553),n=i(11944),a=i(43947),o=i(6628),l=i(7907),u=i(50725);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=this.dbl.db(),t=new o.Migration(r.Schemas.models,e.db,e.dbFile),i=t.migrationsDir.join("20210323_create_tag_fts.sql");await t.applyMigration_(i);const s=c.$tableName;this.dbl.runScript([`INSERT INTO ${s}(${s}) VALUES('delete-all')`]),await u.Tag.ops().batched({qb:e=>e,onResults:e=>(this.insertFts(e),(0,a.delay)(1))})}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},94358:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(13779),s=i(7162),n=i(43414),a=i(11944),o=i(59694),l=i(75556),u=i(8199),c=i(26588),d=i(39784);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},1724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(70283),s=i(11944),n=i(75556),a=i(39784),o=i(7907);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},78053:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeAssetTags_=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(96593),o=i(89452),l=(0,r.lazy)((()=>(0,s.mkLogger)("model.WriteAssetTags")));t.writeAssetTags_=async function(e,t){const i=o.AssetFile.ops().findBy({assetId:e});return(0,n.mapAsync)({name:"writeAssetTags",arr:i,f:e=>async function(e,t){const i=await e.posixFile_();if(null!=i&&!0===await(i?.exists()))return(0,a.writeTags_)(i,t,e.mimetype);l().info("Skipping AssetFile:"+e.id+" (file is missing)",{writeTags:t})}(e,t)})}},77837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(23595),s=(0,i(4866).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},26825:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(11944),s=i(39938),n=i(38625),a=i(44726),o=i(82798);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"ยฌ",and:"โˆง",or:"โˆจ"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},40234:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(13779),s=i(11254),n=i(11944),a=i(59694),o=i(39938),l=i(38625),u=i(84253),c=i(82798),d=i(77837),h=i(26825);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[ยฌ(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},4728:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(50764)),n=i(4866),a=i(7162),o=i(19658),l=i(53525),u=i(75556),c=r(i(12436)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!o.isProd&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},66953:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(4866),s=i(7162),n=i(85590),a=i(68074),o=i(6667),l=i(43414),u=i(61473),c=i(39938),d=i(38625),h=i(87748),f=i(82798),m=i(18273),p=i(30690),g=i(77837),y=i(26825),v=i(40234),w=i(4728),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",M(t));case v.AssetTermNs.excluded:return T({qb:e,column:"Asset.excludedAt",whereNull:0===M(t)});case v.AssetTermNs.deleted:return T({qb:e,column:"Asset.deletedAt",whereNull:0===M(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+_(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+_(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function M(e){return P(e)?1:0}function _(e){return e.includes("*")?e.split("*").map(_).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function T({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},12436:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(34235)),a=i(11944),o=i(82798);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-ยฌ]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|โˆจ|\|{1,2}) +/,and:/(?:and|AND|And|โˆง|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},81520:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDb=void 0;const r=i(4866);t.statsDb=(0,r.lazy)((()=>{}))},89749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statsDbJanitor=void 0;const r=i(19658),s=i(55568),n=i(28807),a=i(91641),o=i(62936),l=i(76915),u=i(88491),c=i(18130),d=i(81520);t.statsDbJanitor=async function(e){const t=new c.Db(o.Schemas.stats,e.join(l.SqliteBase));return(0,s.isStatsDbMigrator)()&&(await t.migrate_(),new n.EndableInterval({name:"statsDbJanitor vacuum",callback:()=>t.vacuum(),intervalMs:r.isTest?20*u.secondMs:5*u.minuteMs,rank:a.EndableRanks.service})),d.statsDb.set(t),t}},97840:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(87489),c=i(24948),d=i(69060),h=i(9483),f=i(7162),m=i(83773),p=i(43414),g=i(96593),y=i(31195),v=i(27446),w=i(15465),b=i(35280),S=i(11944),P=i(39938),M=i(87748),_=i(39784),T=i(49049),E=i(89452);t.mayCopyAssetsToLibrary=async function(){return p.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,f.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!p.Settings.copyAssetsToLibrary.valueOrDefault||await(0,d.l)())return"copyAssetsToLibrary is false";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(p.Settings.libraryDir.valueOrDefault))return e+" already contained by "+p.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,p.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,_.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(E.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),(0,u.submitTask_)("repairAsset",{assetId:t})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t.forceSync);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,g.readCapturedAt)(e),i=(0,m.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,g.readTags)(e);if(null!=i)return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},71766:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(4866),s=i(7162),n=i(46852),a=i(82341),o=i(79015),l=i(76531),u=i(43414),c=i(3874),d=i(10609),h=i(46573),f=i(43947),m=i(75556),p=i(26588),g=i(39784),y=i(85223),v=i(6492);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((()=>(0,p.thenCollect)((0,h.volumes)(),(e=>!0!==e.ignorable&&(0,m.gt0)(e.size)&&!(0,d.isExcludedMountpoint)(e.mountpoint)?(0,v.toUriPath)(e.mountpoint,(0,c.nativePath2uri)(e.mountpoint,e)):void 0))));async function b(){const e=[],i=[];for(const r of(0,g.toA)(u.Settings.scanPaths.value))if(await(0,l.isReadableDirectory)(r)){const s=await(0,v.nativePathToUriPath)(r);null==s?(e.push(r),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",r)):i.push(s)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",r);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,f.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];e.push(...(await b()).result),u.Settings.scanAllDrives.valueOrDefault&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:u.Settings.libraryDir.valueOrDefault,originalsDir:u.Settings.originalsDir.value})));u.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),u.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},85223:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.getStaleCompletedAt=t.bestPathToSync=t.restartSyncAt=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(13779),s=i(4866),n=i(7162),a=i(55568),o=i(14889),l=i(31329),u=i(68074),c=i(82341),d=i(79015),h=i(9483),f=i(43414),m=i(11944),p=i(88491),g=i(43947),y=i(19067),v=i(66776),w=i(75556),b=i(36310),S=i(65548),P=i(71766),M=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));async function _(){const e=await(0,P.pathsToSync)(),t=f.Settings.forceSync.valueOrDefault?[]:await S.Progress.times();return M().tap({msg:"pathsAndTimesToSync()",level:h.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}async function T(e){const i=await(0,t.getStaleCompletedAt)(),s=e.filter((e=>null==e.lastCompletedAt||e.lastCompletedAt({...e,lastStarted:(0,v.map)(e.lastStartedAt,u.tsToLocal),lastCompleted:(0,v.map)(e.lastCompletedAt,u.tsToLocal),lastUpdated:(0,v.map)(e.lastUpdatedAt,u.tsToLocal),incomplete:null==e.lastCompletedAt||e.lastCompletedAte.nativePath)),stale:(0,u.tsToLocal)(i)});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,w.gt)(e.lastUpdatedAt,Date.now()-15*p.minuteMs))return M().info("bestStable(): returning most recently updated",e),{...e,why:"recently updated"}}{const e=s.find((e=>null==e.lastStartedAt));if(null!=e)return M().info("bestStable(): returning neverStartedBefore",e),{...e,why:"never synced before"}}{const e=s.find((e=>null==e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning neverCompletedBefore",e),{...e,why:"never completed before"}}{const e=(0,r.leastBy)(s,(e=>e.lastCompletedAt));if(null!=e)return M().info("bestStable(): returning leastRecentlyCompleted",e),{...e,why:"least recently synced"}}M().info("bestPathToSync(): all paths have been recently completed (yay)."),(0,a.isSyncService)()&&(M().info("bestPathToSync(): Marking sync as complete."),b.Operation.markOpCompleted({name:b.OperationNames.forceRestartSync}))}function E(e,t){return null==e.lastStartedAt?"new":(0,w.gt)(e.lastUpdatedAt,Date.now()-10*p.secondMs)&&!(0,w.closeTo)(e.lastCompletedAt,e.lastUpdatedAt,5*p.secondMs)?"syncing":(0,w.gt)(e.lastCompletedAt,t)?"synced":"stale"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*p.secondMs?"just now":(0,y.fmtDuration)(t)+" ago"}t.nativePathBlocklist=new l.TTLSet(10*p.minuteMs),t.pathsAndTimesToSync=_,t.restartSyncAt=async function(){const e=await _();return Math.min(...(0,m.compact)([Date.now(),...e.map((e=>e.lastCompletedAt))]))+f.Settings.syncNewIntervalMs.valueOrDefault},t.bestPathToSync=async function(){return T(await _())},t.getStaleCompletedAt=(0,s.lazy)((async()=>{const e=b.Operation.getFirstPendingOp({name:b.OperationNames.forceRestartSync});return e?.createdAt??Date.now()-f.Settings.syncNewIntervalMs.valueOrDefault}),o.ShortCommandTimeoutMs),(0,g.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getStaleCompletedAt.unset())))),t.bestStable=T,t.syncPathsForUI=async function(){const e=await _(),i=await T(e),r=await(0,t.getStaleCompletedAt)(),s=(0,c.libraryOriginalsDirPosixFile)()?.nativePath;return e.map((e=>({path:e.nativePath,library:s===e.nativePath,status:E(e,r),isNext:e.nativePath===i?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},6492:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUriPath=t.posixFileToUriPath=t.toUriPath=void 0;const r=i(3874);async function s(e,t){const i=await t;if(null!=i)return{nativePath:e,uri:i.toString()}}t.toUriPath=s,t.posixFileToUriPath=async function(e){return s(e.nativePath,await e.uriObject_())},t.nativePathToUriPath=async function(e){return s(e,(0,r.nativePath2uri)(e))}},54578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.AssetCountForTagQuery=void 0;const r=i(7162),s=i(7383),n=i(11978),a=i(88491),o=i(43383),l=i(43947),u=i(75556),c=i(44726),d=(0,o.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function h(e,i=[]){const r=e.prepare(t.AssetCountForTagQuery).pluck(),a=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId");return(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e)(0,s.timeSync)("db.rebuildTagAssetCounts",(()=>{const e=r.get({tagId:t});a.run({tagId:t,assetCount:e,updatedAt:Date.now()}),d().debug("_rebuildTagAssetCounts()",{tagId:t,assetCount:e})})),t%10==0&&await(0,l.delay)(1)}})}t.AssetCountForTagQuery=(0,c.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.rebuildTagAssetCounts=async function(e,t=a.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>h(e,["assetCount IS NULL"]))),(0,u.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rh(e)))}},63216:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.vacuumOrphanTags=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(49411)),n=i(4866),a=i(7162),o=i(19658),l=i(99869),u=i(97503),c=i(7383),d=i(79015),h=i(18501),f=i(47874),m=i(43414),p=i(61473),g=i(47044),y=i(55412),v=i(32421),w=i(53719),b=i(46573),S=i(39938),P=i(88491),M=i(43947),_=i(19067),T=i(75556),E=i(8199),D=i(44726),k=i(11254),x=i(89452),C=i(50725),F=i(21250),I=i(54578),A=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return A().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=(o.isTest?5:30)*P.secondMs;async function L(e=Date.now()-10*P.minuteMs){C.Tag.dbl.runf((t=>t.where({assetCount:0}).where("createdAt","<",e).whereNotNull("parentId").del()))}t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=A().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.info("updating tag mountpoints..."),await R(),i.recountAllTags&&(s.info("rebuilding tag asset counts..."),await(0,I.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0),s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)()),s.info("vacuuming orphan tags..."),await L()}catch(e){A().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),A().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}}),t.vacuumOrphanTags=L;const R=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{const e=C.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await B(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function N(){t.tagFtsRebuild.unset(),R.unset()}async function B(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",N),m.Settings.libraryDir.watchLater(N)})),t.fixFileRootTag=B,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,M.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},72316:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(34261).install()}catch{}const r=i(37980),s=i(64063),n=i(9972),a=i(37445),o=i(7127),l=i(51731),u=i(92045),c=i(21625);!async function(){await new r.CLI(o.ServiceNames.web).add(l.ExposeArg,u.LogArgs,n.TimingArg,a.WriteSettingsArg,s.ColorArgs).parse(),new c.WebService}()},36389:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AboutRouter=void 0;const s=r(i(66860)),n=i(14889),a=i(91464),o=i(80294),l=i(77368),u=i(69060),c=i(43414),d=i(47044),h=i(46573),f=i(38625),m=i(88491),p=i(19067),g=i(66776),y=i(75556),v=i(26588),w=i(20636),b=i(17078),S=i(98505),P=i(65548),M=i(85223),_=i(47458);t.AboutRouter=class{router(){return s.default.Router().get("/about",(0,l.wrap)("AboutRouter",this.about.bind(this)))}async about(e,t,i){const r=n.ShortCommandTimeoutMs+m.secondMs,s=await(0,w.thenOrTimeoutAs)({f:(0,S.systemInformation)(),timeoutMs:r,as:[{term:"System information",defn:"Failed to fetch system information: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"}]}),l=await(0,w.thenOrTimeout)((0,v.thenMap)((0,h.volumes)(),(e=>e.map((e=>({ignorable:e.ignorable,mountpoint:e.mountpoint,uuid:e.uuid,volsha:(0,g.map)(e.uuid,d.volsha),size:(0,b.fmtBytes)(e.size,2),free:(0,b.fmtBytes)(e.available,2),full:(0,y.gt0)(c.Settings.minDiskFreeGb.valueOrDefault)&&(0,y.lt)(e.available,c.Settings.minDiskFreeGb.valueOrDefault*b.GB),label:e.label,remote:!0===e.remote?{remote:e.remote,host:e.remoteHost,share:e.remoteShare}:void 0}))).filter((e=>!0!==e.ignorable)))),r);l===w.Timeout&&s.push({term:"volumes() timeout",defn:"Failed to fetch volume metadata: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"});const T=null==P.Progress.db()?void 0:await(0,w.thenOrTimeout)((0,M.syncPathsForUI)(),n.ShortCommandTimeoutMs);T===w.Timeout&&s.push({term:"sync paths timeout",defn:"Failed to fetch sync path metadata: timeout after "+(0,o.fmtMs)(n.ShortCommandTimeoutMs),defnClass:"fail"});const E=await(0,u.b)();return(0,_.render)(e,t,"about",{title:"About PhotoStructure",systemInfo:s,volumes:Array.isArray(l)?l.map((e=>({...e,mountpoint:(0,a.wbrPath)(e.mountpoint)}))):void 0,syncPaths:Array.isArray(T)?T:void 0,subTier:await(0,u.t)(),subTrial:(0,f.isTrue)(E?.l?.trial),subEmail:E?.l?.sub,subExpiresInDuration:(0,g.map)(E?.l?.exp,(e=>(0,p.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,g.map)(E?.l?.exp,m.fmtIsoDate)})}}},86840:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AdminPostRouter=void 0;const s=r(i(66860)),n=i(2126),a=i(79015),o=i(77368),l=i(68079),u=i(50080),c=i(75123),d=i(79403),h=i(82041),f=i(46573),m=i(88491),p=i(43947),g=i(87748),y=i(17146),v=i(9075),w=i(59960),b=i(3382),S=2*m.secondMs;t.AdminPostRouter=class{router(){return s.default.Router().post("/admin/restart",(0,o.wrap)("AdminHealthRouter:restart",this.restart.bind(this))).post("/admin/bounce",(0,o.wrap)("AdminHealthRouter:bounce",this.bounce.bind(this))).post("/admin/refresh/:id",(0,o.wrap)("AdminHealthRouter:refresh",this.refresh.bind(this))).post("/admin/clear-library",(0,o.wrap)("AdminHealthRouter:clear-library",this.clearLibrary.bind(this))).post("/admin/clear-caches",(0,o.wrap)("AdminHealthRouter:clear-caches",this.clearCaches.bind(this))).post("/admin/recheck-tools",(0,o.wrap)("AdminHealthRouter:recheck-tools",this.recheckTools.bind(this))).post("/admin/repair-db",(0,o.wrap)("AdminHealthRouter:repair-db",this.repairDb_.bind(this))).post("/admin/run-maintenance",(0,o.wrap)("AdminHealthRouter:repair-db",this.maintenance_.bind(this))).post("/admin/shutdown",(0,o.wrap)("AdminHealthRouter:shutdown",this.shutdown.bind(this)))}async restart(e,t,i){await(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarted library...",timeout:S},url:"/splash"})}async refresh(e,t,i){const r=e.params.id,s=d.HealthCheck.findById(r);if(null==s)throw new Error("No health check found with id="+(0,g.stringify)(r));const n=await s.refresh();(0,u.sendRedirectionToast)({response:t,toast:{text:"Health check "+r+": "+n.level,timeout:S},url:"/health"})}async bounce(e,t,i){(0,p.delay)(m.secondMs).then((()=>(0,n.exit)({reason:"/bounce requested by "+e.ip,status:0}))),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarting webserver...",timeout:15*m.secondMs},url:"/splash"})}async clearLibrary(e,t,i){await(0,h.clearLibraryDirSetting)(),(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Prior library was unset. Restarting...",timeout:S},url:"/splash"})}async clearCaches(e,t,i){await(0,f.clearVolumesCache)({deleteFileCache:!0}),await(0,c.clearReaddirCaches)(),(0,a.ee)().emit("clearCache"),"/health"===(0,l.referrer)(e)?(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared caches.",timeout:S},url:"/health"}):(0,u.sendServerToast)({response:t,toast:{text:"Cleared caches."},reload:!0})}async recheckTools(e,t,i){(0,a.ee)().emit("clearToolCache"),(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared tool caches.",timeout:S},url:"/health"})}async repairDb_(e,t,i){(0,b.dbModelRepair)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library database repair...",timeout:S},url:"/splash"})}async maintenance_(e,t,i){(0,y.cleanup_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library maintenance jobs...",timeout:S},url:"/"})}async shutdown(e,t,i){(0,p.delay)(S).then((()=>(0,w.shutdown)("requested by "+e.ip))),(0,u.sendServerToast)({response:t,toast:{text:"Shutdown initiated."}})}}},16654:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiAssetRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(70283),o=i(46852),l=i(21142),u=i(80294),c=i(79141),d=i(87489),h=i(77368),f=i(50080),m=i(34928),p=i(69060),g=i(72612),y=i(15203),v=i(43414),w=i(53719),b=i(11944),S=i(59694),P=i(13783),M=i(38625),_=i(88491),T=i(66776),E=i(75556),D=i(61570),k=i(33714),x=i(86768),C=i(11254),F=i(82798),I=i(30690),A=i(10074),O=i(63232),L=i(50725),R=i(78053),N=(0,n.mkLogger)("web.ApiAssetRouter"),B=["hidden","excludedAt","deletedAt"];t.ApiAssetRouter=class{constructor(e){this.previews=e}wrapApi(e,t){return(i,r,s)=>(0,f.wrapWithToast)({response:r,f:async()=>{const s=(0,E.toGt0)(i.params.assetId);if(null==s)return r.sendStatus(400);const n=await(0,o.thenMapOr)(I.Asset.ops().findById(s,{shown:1}),(e=>t(i,s,e)),(()=>this.onMissingAsset(i,s)));if(N.debug(e,{result:n}),null!=n)return(0,h.jsonOrRedirect)(n,r);throw new c.WrappedError("Asset "+s+" wasn't found",{retriable:!1,doNotSend:!0,fatal:!1})}})}router(){return s.default.Router().get("/api/asset/:assetId/info",this.wrapApi("ApiAssetRouter.assetInfo",this.assetInfo.bind(this))).get("/api/asset/:assetId/streams",this.wrapApi("ApiAssetRouter.assetInfo",this.assetStreams.bind(this))).get("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.asset",this.asset.bind(this))).put("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.save",this.save.bind(this))).put("/api/asset/:assetId/resync",this.wrapApi("ApiAssetRouter.resync",this.resync.bind(this)))}async assetInfo(e,t,i){const r=i.getAssetFiles(),s=i.getShown(),n=(0,T.map)(s,(e=>e.getNativePath())),a=(0,g.isLocalhost)(e.ip)&&!(0,y.isDocker)();if(v.Settings.resyncAssetOnVisit.valueOrDefault&&(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!1,forceRebuildPreviews:!1}),null==s||null==n)return void N.error("no shown AssetFile found for "+t,{asset:i,shown:s,shownPathP:n});N.debug("assetInfo()",{assetId:t,shown:s,shownPathP:n,ip:e.ip,showOpenFile:a});const l=i.getTags(),c=await(0,o.mapAsync)({name:"api.assetInfo.tags",arr:l,f:e=>e.toApiTag()}),f=await(0,o.mapAsync)({name:"api.assetInfo.files",arr:r,f:e=>e.toApi(this.previews,s.sha)});return(0,S.sortByInPlace)(f,(e=>[!e.shown,!e.exists,e.nativePath])),{assetId:t,capturedAtLocale:s.capturedAtLocale((0,h.requestLang)(e)),...(0,D.pick)(s,"mimetype","focalLength","iso","aperture","shutterSpeed"),durationHMS:(0,T.map)(s.durationMs,u.durationHMS),fps:s.fps,files:f,tags:c,showOpenFile:a}}async onMissingAsset(e,t,i){const r="next"===e.query.from;N.info("onMissingAsset()",{query:(0,D.entries)(e.query),params:(0,D.entries)(e.params),assetId:t});const s=(0,E.toInt)(String(e.query.priorAssetId)),n=(0,T.mapOr)(i,(e=>e.id),(()=>s));if(null==n)return void N.warn("onMissingAsset(): no context asset available");const l=await(0,o.thenMapOr)(i,(e=>e.capturedAtLocal),(()=>I.Asset.dbl.pluckFirstf((e=>e.select("capturedAtLocal").where({id:n})))));let u=I.Asset.shownUnhidden(I.Asset.query().select("id").limit(1).whereNotIn("id",(0,b.compact)([t,s])));u=r?u.andWhere("capturedAtLocal","<",l).orderBy("capturedAtLocal","desc"):u.andWhere("capturedAtLocal",">",l).orderBy("capturedAtLocal","asc");const c=I.Asset.dbl.pluckFirst(u);return N.warn("Asset redirect",{fromAssetId:n,priorAssetId:s,fromTime:l,toAsset:c}),(0,a.mapGt0)(c,(t=>(0,x.mkReplace)((0,P.assetUrl)({assetId:t,params:[e.query,e.params]}),{text:`Asset ${n} is no longer available.`,type:"info"})))}async asset(e,t,i){const r=i.getShown();if(null==r)return N.error("no shown AssetFile found for "+t+", disabling (for now)."),i.upsert({shown:!1}),N.error("Asset un-shown."),(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i);i.getBeforeAfterId();const s={...i.partialSimpleAsset(),name:r.basename,width:r.width,height:r.height,rotation:r.rotation??0,capturedAtLocale:r.capturedAtLocale((0,h.requestLang)(e)),aspectRatio:(0,m.aspectRatio)(r),durationHMS:(0,T.map)(r.durationMs,u.durationHMS),downloadable:await r.originalDownloadable({brief:!0}),contextTag:await i.whenApiTag(),beforeAssetId:i.beforeId,afterAssetId:i.afterId};if(r.isVideo){const r=await i.videoSources();return await i.getExistingAssetFiles(),(0,b.isEmpty)(r)?(N.warn("no existing files for "+t+", trying to repair, but redirecting user now."),(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i)):{...s,videoAttrs:i.videoAttrs(),videoSources:r}}return{...s,imgAttrs:await i.fitAttrs(this.previews)}}async assetStreams(e,t,i){const r=(0,E.toInt)((0,F.toS)(e.query.limit),{defaultValue:C.BeforeAfterStreamLimit}),s=i.getStreams(r);return N.tap({msg:"assetStreams",result:{assetId:t,assetStreams:await(0,o.mapAsync)({name:"assetStreams",arr:s,f:e=>e.toApi()})}})}async save(e,t,i){if(await(0,p.l)())return N.warn("save(): disabled"),{showTryPlusToast:!0};const r=i.isActive(),s={hidden:(0,M.toBoolean)(e.body.hidden),excludedAt:(0,T.map)((0,M.toBoolean)(e.body.excluded),(e=>e?Date.now():null)),deletedAt:(0,T.map)((0,M.toBoolean)(e.body.deleted),(e=>e?Date.now():null)),rating:(0,T.map)((0,M.toBoolean)(e.body.liked),(e=>e?v.Settings.likeRating.valueOrDefault:null))};if(!(0,b.isEmpty)((0,D.keys)(s))){N.info("save()",{obj:s,body:e.body}),A.AssetRevision.insert(...(0,D.entries)((0,D.omit)(s,...B)).map((([e,r])=>({assetId:t,field:e,priorValue:i?.[e],newValue:r}))));const n=null===s.deleted?null:null!=s.deleted?-1:s.rating;void 0!==n&&await(0,R.writeAssetTags_)(t,{Rating:n}),i.upsert(s),i.isActive()!==r&&L.Tag.deltaAssetCountAndAncestors(i.tagIds(),i.isActive()?1:-1)}const n=i.partialSimpleAsset(),a=(0,k.normalizeRotation)((0,E.toInt)(e.body.rotation));return null!=a&&0!==a&&(await(0,O.setAssetRotation_)(t,a,this.previews),n.rotation=a),n}async resync(e,t){I.Asset.dbl.runf((e=>e.where({id:t}).update({version:0})));const i=()=>I.Asset.dbl.pluckFirstf((e=>e.where({id:t}).select("updateCount"))),r=i();return(0,d.submitTask_)("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),await(0,l.untilTrue)((async()=>r!==i()),{timeoutMs:(0,w.commandTimeoutMs)(),intervalMs:_.secondMs}),{v:i()}}}},47576:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressRouter=void 0;const l=i(92332),u=i(4866),c=i(14889),d=i(41749),h=i(232),f=i(67220),m=i(11944),p=i(24603),g=i(73491),y=i(65548);class v extends d.ServerSentEventsRouter{constructor(e){super(g.ApiProgressPath),r.add(this),this.updatesProvider=e,s.set(this,void 0),this.updateData=(0,u.lazy)((()=>this.updatesProvider.updates()),(0,y.ProgressRateMs)()),o(this,s,(0,l.setInterval)((()=>a(this,r,"m",n).call(this)),(0,y.ProgressRateMs)()),"f"),this.onEnds.push((()=>clearInterval(a(this,s,"f"))))}firstEvents(){return[]}}t.ProgressRouter=v,s=new WeakMap,r=new WeakSet,n=async function(){if(!(this.ended||(0,m.isEmpty)(this.streams)||(0,f.isPaused)()&&null!=this.updateData.prior()))try{const e=await this.updateData.prior(),t=await this.updateData.refresh();if(null==t)return void this.logger.warn("Failed to fetch updates");if((0,p.eql)(e,t))return void this.updateData.setTTL(Math.min(c.ShortCommandTimeoutMs,this.updateData.ttl()??(0,y.ProgressRateMs)())+500);if(this.ended)return;this.updateData.setTTL((0,y.ProgressRateMs)());const i=(0,h.mkEventStream)({data:t});for(const e of this.streams)e.write(i)}catch(e){this.logger.warn("Failed to send updates",e)}}},6757:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSearchRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(22189),l=i(43414),u=i(46573),c=i(11944),d=i(39938),h=i(38625),f=i(75556),m=i(17078),p=i(24760),g=i(82798),y=i(30690),v=i(14405),w=i(26825),b=i(40234),S=i(4728),P=i(66953),M=(0,n.mkLogger)("web.ApiSearchRouter");t.ApiSearchRouter=class{router(){return s.default.Router().get("/api/search",(0,a.wrap)("ApiSearchRouter.get",this.get.bind(this)))}async get(e,t){const i=(0,g.toStr)(e.query.q," "),r=p.AssetQueryOrderByColumns.validOrElse((0,g.toStr)(e.query.orderby,","),p.AssetQueryOrderByColumns.capturedAt),s=(0,h.isTrue)(e.query.asc),n={column:r===p.AssetQueryOrderByColumns.capturedAt?"Asset.capturedAtLocal":"Asset.updatedAt",order:s?"asc":"desc"},a=(0,f.toGt0)((0,g.toStr)(e.query.offset));if(M.debug("get()",{q:i,orderBy:n,offset:a}),(0,d.blank)(i))return t.json({});const _=(0,b.normalizeQuery)((0,S.parseQuery_)(i));let T=(0,P.defaultAssetQuery)().select({id:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"}).orderBy([n,"Asset.id"]).limit(512);const E=(0,w.findTerm)(_,(e=>"fs"===e.ns))?await(0,u.mountpointToVolsha)():void 0;null!=a&&(T=T.offset(a));const D=null==a?await async function(e,t,i){const r=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().countDistinct("Asset.id"),t))}(t,i),{emptyTrashQuery:s,removeAssetsQuery:n}=function(e){const t=1===(0,w.flatTerms)(e).length,i=t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.deleted)));return{emptyTrashQuery:i,removeAssetsQuery:!i&&t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.excluded)))}}(t);if(0===r)return{description:s?"No assets are marked for trash.":n?"No assets are marked for removal.":"No matching assets."};const a="Found "+(0,m.plur)(r,"asset");if(!s&&!n)return{description:a};const u=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().join("AssetFile","AssetFile.assetId","Asset.id").countDistinct("AssetFile.id"),t))}(t,i),c=a+" ("+(0,m.plur)(u,"file")+")",d={expectedAssetFileCount:String(u)};if(s){const t="Empty trash";return{description:c,buttonText:t,buttonIcon:"trash_forever",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableEmptyTrash.valueOrDefault?{buttonClass:"error",buttonTitle:null,prompt:[`

    Are you sure you want to permanently delete ${(0,m.plur)(u,"file")} comprising ${(0,m.plur)(r,"asset")}?

    `,"","

    To proceed, please enter the number of files that will be deleted:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/empty-trash",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableEmptyTrash" setting.',prompt:null,formAction:null}}}if(n){const t="Remove assets";return{description:c,buttonText:t,buttonIcon:"warning",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableRemoveAssets.valueOrDefault?{buttonClass:"warning",buttonTitle:null,prompt:["

    Are you sure you want to remove "+(0,m.plur)(r,"asset")+" (comprised of "+(0,m.plur)(u,"file")+") from your library?

    ","","

    To proceed, please enter the number of files that will be removed:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/remove-assets",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableRemoveAssets" setting.',prompt:null,formAction:null}}}throw new Error("internal error (mkBanner)")}(e,_,E):void 0;T=(0,P.queryToSql)(_,T,E).distinct();const k=(0,c.compact)(y.Asset.dbl.all(T).map(v.toAssetId)),x={query:{q:i,normalized:(0,w.queryToString)(_,w.NormieQuerySymbols),orderBy:r,asc:s,offset:a??0,nextOffset:k.length<512?void 0:k.length+(a??0)},banner:D,assetIds:k};return M.debug(".get("+(0,w.queryToString)(_)+") result",x),t.json(x)}validatePostRequest(e,t){return M.debug("validatePostRequest",{req_query:e.query,req_body:e.body}),this.validatePost((0,g.toStr)(e.query.expectedAssetFileCount," "),e.body.answer,t)}async validatePost(e,t,i){M.debug("validatePost",{expectedAssetFileCount:e,answer:t});const r=(0,f.toInt)((0,g.toS)(e));if(null==r)return"Cancelled: the expected number of files was missing from the request.";const s=(0,f.toInt)(t);if(null==s)return"Cancelled: missing user input.";const n=await y.Asset.dbl.pluckFirst(i().join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id"));return r!==n?`Cancelled: the number of files has changed from ${(0,m.fmt)(r)} to ${(0,m.fmt)(n)}. Reload this page and try again.`:s!==r?`Cancelled: you entered "${t??""}" and we expected "${r}".`:{assetFileCount:n}}}},40687:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSplashRouter=void 0;const a=i(41749),o=i(79403),l=i(42041),u=i(88491),c=i(61715),d={loading:"โณ Loading...",welcome:"๐Ÿ‘‹ Welcome!",ready:"โœ… Ready",failed:"โš ๏ธ Something's not right. Gathering details..."};class h extends a.ServerSentEventsRouter{constructor(){super("/sse/splash"),r.set(this,null)}runStateEvent(e=o.HealthCheck.runState()){const t=e===c.RunStates.loading;return t&&this.streams.length>0?n(this,r,s(this,r,"f")??setInterval((()=>{this.writeToStreams(this.runStateEvent())}),u.secondMs),"f"):null!=s(this,r,"f")&&(clearInterval(s(this,r,"f")),n(this,r,null,"f")),this.logger.tap({msg:"runStateEvent()",level:"warn",result:t?{event:"msg",data:o.HealthCheck.loadingMsg()??d[e]}:{event:"settled",data:d[e]},meta:{state:e}})}firstEvents(){return[{event:"version",data:l.version},this.runStateEvent()]}}t.ApiSplashRouter=h,r=new WeakMap},34312:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSystemRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(70283),l=i(38307),u=i(56958),c=i(87489),d=i(77368),h=i(50080),f=i(76531),m=i(24948),p=i(43414),g=i(67220),y=i(11944),v=i(39938),w=i(38625),b=i(75117),S=i(87748),P=i(75556),M=i(17078),_=i(82798),T=i(64303),E=i(59960),D=i(30690),k=i(36310),x=(0,n.lazy)((()=>(0,a.mkLogger)("web.ApiSystemRouter")));async function C(e,t){var i,r;return x().tap({msg:`countAssetFiles(${t})`,result:(i=e.locals)[r="countAssetFiles-"+t]??(i[r]=await D.Asset.dbl.pluckFirst(D.Asset.shownRemovable(t).join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id")))})}function F(e){return async(t,i,r)=>{const s=(0,_.toStr)(t.query.expectedAssetFileCount," "),n=(0,o.extractInt)(t.body.answer);x().debug("validatePostCounts",{expectedAssetFileCount:s,answer:n});const a=(0,P.toInt)((0,_.toS)(s));if(null==a)return(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:"The expected number of files was missing from the request"}});const l=(0,P.toInt)(n);if(null==l)return(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:"User answer was missing"}});const u=await C(i,e);return a!==u?(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:`The number of files has changed from ${(0,M.fmt)(a)} to ${(0,M.fmt)(u)}. Reload this page and try again.`}}):l!==a?(0,h.sendWarningServerToast)({response:i,toast:{text:"Cancelled",details:`You entered "${n??""}" and we expected "${a}".`}}):r()}}function I(e){if("deletedAt"===e)return k.OperationNames.applyDeleted;if("excludedAt"===e)return k.OperationNames.applyExcluded;throw new Error("invalid RemovableColumn "+e)}async function A(e,t){const i=await async function(e,t){var i,r;return(i=e.locals)[r="countAssets-"+t]??(i[r]=await D.Asset.dbl.pluckFirst(D.Asset.shownRemovable(t).countDistinct("Asset.id")))}(e,t),r=await C(e,t);x().warn("setting "+t+" to unshown...",{assetCount:i,assetFileCount:r});const s=k.Operation.ops().insertOne({name:I(t),value:(0,S.stringify)({assetCount:i,assetFileCount:r})});x().warn("inserted",{ops:s});const n={shown:0,updatedAt:s.createdAt};n[t]=s.createdAt;const a=D.Asset.dbl.run(D.Asset.shownRemovable(t).update(n));x().warn("updated assets",{result:a,obj:n}),await(0,c.submitTask_)("checkOperations")}async function O(e,t){return await A(t,"deletedAt"),(0,h.sendServerToast)({response:t,reload:!0,toast:{text:"Emptied trash",details:"Files will be deleted soon.",type:"success"}})}async function L(e,t){return await A(t,"excludedAt"),(0,h.sendServerToast)({response:t,reload:!0,toast:{text:"Assets have been removed from your library.",type:"success"}})}t.ApiSystemRouter=class{constructor(e){this.openFileService=e,this.getState=(e,t)=>{const i={paused:(0,g.isPaused)()};return t.json(i)},this.getHasEmail=(e,t)=>{t.json({hasEmail:(0,b.isEmailMaybe)(p.Settings.email.value)})},this.postSystem=async(e,t)=>{const i=e.body,r=[];x().info("post()",{body:e.body}),(0,w.mapTrue)(i.pause,(()=>{(0,u.broadcastPause)(),r.push("Sync was paused")})),(0,w.mapTrue)(i.resume,(()=>{(0,u.broadcastResume)(),r.push("Sync was resumed")})),await(0,w.mapTrue)(i.restartSync,(async()=>{l.StdoutWrite.restartSync(),r.push("Sync restart was requested")})),await(0,w.mapTrue)(i.forceRestartSync,(async()=>{k.Operation.markOpCompleted({name:"forceRestartSync"},{value:"canceled (force-restarted)"}),k.Operation.ensurePendingOp({name:"forceRestartSync"}),l.StdoutWrite.restartSync(),r.push("Sync force-restart was requested")})),await(0,w.mapTrue)(i.rebuildLibrary,(async()=>{(0,T.forceRebuildLibrary)(),l.StdoutWrite.restartSync(),r.push("Library rebuild was requested")})),(0,w.mapTrue)(i.showSyncReports,(()=>{this.openFileService((0,m.syncReportReadme)()),r.push("Opened your sync reports directory")}));const s=(0,_.toS)(i.syncDir);(0,v.notBlank)(s)&&await(0,f.exists)(s)&&(0,c.submitTask_)("syncDir",{nativePath:s}),(0,w.mapTrue)(i.shutdown,(async()=>{const t="requested by "+e.ip;(0,E.shutdown)(t),r.push("Shutdown "+t)})),(0,y.isNotEmpty)(r)?(0,h.sendServerToast)({response:t,toast:{type:"info",text:r.join(". ")}}):(t.status(400),(0,h.sendServerToast)({response:t,toast:{text:"Nothing requested.",type:"warning"}}))}}router(){return s.default.Router().get("/api/system/state",(0,d.wrap)("state",this.getState)).get("/api/system/hasEmail",(0,d.wrap)("hasEmail",this.getHasEmail)).post("/api/system",((e,t)=>(0,h.wrapWithToast)({response:t,f:()=>this.postSystem(e,t)}))).post("/api/system/empty-trash",h.requirePlus,(0,h.requireEnabled)(p.Settings.enableEmptyTrash),F("deletedAt"),O).post("/api/system/remove-assets",h.requirePlus,(0,h.requireEnabled)(p.Settings.enableRemoveAssets),F("excludedAt"),L)}}},47967:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiTagRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(70283),o=i(14889),l=i(80294),u=i(77368),c=i(50080),d=i(43414),h=i(19209),f=i(11944),m=i(75556),p=i(86768),g=i(11254),y=i(48652),v=i(82798),w=i(49374),b=i(30690),S=i(50725),P=(0,n.mkLogger)("ApiTagRouter");function M({name:e,f:t}){return(0,u.wrap)(e,(async(i,r)=>{const s=(0,m.toInt)(i.params.tagId),n=(0,u.extractTagPath)(i.path).map(h.percentDecode),a=(0,u.getSeed)(i),o=(0,u.getFit)(i),l=(0,f.mapNotEmptyOr)(n,(e=>S.Tag.findByIdOrPath(s,e)),(()=>S.Tag.root())),d=null==l?void 0:t(i,l,{tagId:l.id,tagPath:l.path,seed:a,fit:o});return P.debug(e,{result:d,tagPath:n,seed:a,url:i.url}),null==l||null==d?(0,c.send404Toast)({text:"Failed to find tag "+s??n.join("/"),response:r}):(0,u.jsonOrRedirect)(d,r)}))}t.ApiTagRouter=class{router(){return s.default.Router().get("/api/tag*",M({name:"ApiTagRouter.tagGallery",f:this.tagGallery.bind(this)})).get((0,g.nextAssetsUrl)(":tagId",{}),M({name:"ApiTagRouter.tagAssets",f:this.tagAssets.bind(this)})).get((0,g.nextChildTagsUrl)(":tagId",{}),M({name:"ApiTagRouter.childTags",f:this.childTags.bind(this)}))}tagGallery(e,t,i){if(P.debug("tagGallery()",{tag:t}),null==i.seed)return P.debug("tagGallery(): no seed, redirecting..."),(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query));if(d.Settings.fastForwardEmptyTags.valueOrDefault){const i=t.firstNonInterstitialTagId();if(i!==t.id){const t=S.Tag.findById(i);if(null!=t)return(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query),{text:"Skipping to first non-empty child tagโ€ฆ",uuid:"redirect-to-tag",onlyShowUuidOnce:!0,type:"info"})}}const r={fullPath:e.originalUrl,fit:i.fit,...t.toApiTag(),...this.childTags(e,t,i),...this.tagAssets(e,t)};return 0===t.id&&0===b.Asset.shownCount()&&((0,l.isRecentMs)(w.Library.instance()?.start,o.ShortCommandTimeoutMs)?r.startingUp=!0:r.emptyLibrary=!0),r}childTags(e,t,i){const r=(0,m.toInt)((0,v.toS)(e.query.offset))??0,s=(0,m.toInt)((0,v.toS)(e.query.limit))??4;P.debug("childTags() got ",{thisOffset:r,limit:s,query:e.query});const n={tagId:t.id,offset:r,limit:s,seed:i.seed};n.limit=(0,a.firstGt0)(n.limit,4);const o=t.getChildrenCount(),l=0===o?[]:t.getPagedChildren(n);P.debug("childTags()",{crit:n,childTagCount:o,children:l});const u=l.length+r,c=u{const t=e.getRelatedAssetIds({seed:i.seed+e.id,limit:g.ThumbsPerSample});return(0,f.isNotEmpty)(t)?{...e.toApiTag(),assetIds:t}:void 0})));return P.tap({msg:"childTags result",result:{tagId:t.id,childTags:d,childTagCount:o,nextChildTags:c},meta:{nextOffset:u}})}tagAssets(e,t){const i={offset:(0,m.toInt)((0,v.toS)(e.query.offset),{defaultValue:0})},r=t.getPagedAssetIds(i),s=r.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetOpenGraph=void 0;const r=i(13779),s=i(19371),n=i(43414),a=i(27446),o=i(75556);t.getAssetOpenGraph=async function(e,t){if(null==(t=(0,o.toGt0)(t))||!(0,o.gt0)(n.Settings.openGraphTargetWidth.valueOrDefault))return;const i=s.Previews.instance()?.ap(t);if(null==i)return;const l=await i.readInfo();if(null==l)return;const u=[];if((0,a.isVideoMimeType)(l.mimetype)){u.push({property:"og:video",content:e.with({path:"/video/"+t}).toString()});const r=await i.mp4().exists()?"video/mp4":l.mimetype;u.push({property:"og:video:type",content:r},{property:"og:video:width",content:l.width.toString()},{property:"og:video:height",content:l.height.toString()})}else{const s=(await i.widths("fit")??[]).map((e=>({width:e,path:"/img/"+t+"/fit/"+e})));"image/jpeg"===l.mimetype&&s.push({width:l.width,path:"/img/"+t+"/actual"});const a=(0,r.leastBy)(s,(e=>Math.abs(e.width-n.Settings.openGraphTargetWidth.valueOrDefault)));if(null!=a){u.push({property:"og:image",content:e.with({path:a.path}).toString()},{property:"og:image:type",content:"image/jpeg"},{property:"og:image:width",content:a.width.toString()});const t=a.width/(l.width/l.height);(0,o.gt0)(t)&&u.push({property:"og:image:height",content:Math.round(t).toString()})}}return u}},28631:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cspHandler=void 0;const s=r(i(47806)),n=i(4866),a=i(7162),o=i(43414),l=i(83769),u=i(11944),c=(0,n.lazy)((()=>(0,a.mkLogger)("web.WebSecurity")));t.cspHandler=function(e,t,i){(e.secure||(0,l.isHttpsRequest)(e.headers))&&null==o.Settings.upgradeInsecureRequests.value&&(c().warn('Secure https request detected: setting "upgradeInsecureRequests" to true.'),o.Settings.upgradeInsecureRequests.tmpValue=!0);const r=(0,u.compactBlanks)(["'self'",o.Settings.cspDirective.valueOrDefault]),n=(0,u.compactBlanks)(["'self'","'strict-dynamic'",`'nonce-${t.locals.cspNonce}'`,o.Settings.cspDirective.valueOrDefault]);s.default.contentSecurityPolicy({directives:{defaultSrc:["'self'"],scriptSrc:n,styleSrc:r,baseUri:r,formAction:["'self'","https://account.photostructure.com"],objectSrc:["'none'"],upgradeInsecureRequests:o.Settings.upgradeInsecureRequests.valueOrDefault?[]:null},reportOnly:o.Settings.cspReportOnly.valueOrDefault})(e,t,i)}},23163:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requestAssetRepair=t.ImgActualRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(87489),o=i(77368),l=i(50080),u=i(35254),c=i(66776),d=i(75556),h=i(61570),f=i(30690),m=i(89452),p=(0,n.mkLogger)("web.ImgActualRouter");function g(e){return(0,a.submitTask_)("repairAsset",{assetId:e,forceSync:!0,forceRebuildPreviews:!0})}t.ImgActualRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/img/:assetId/:assetFileId/actual(.*)?",(0,o.wrap)("ImgActualRouter.assetImg",this.assetFileImg.bind(this))).get("/img/:assetId/actual(.*)?",(0,o.wrap)("ImgActualRouter.assetImg",this.assetImg.bind(this))).get("/dl/:assetId/:assetFileId",(0,o.wrap)("ImgActualRouter.assetFileImg",this.assetFileImg.bind(this)))}async assetImg(e,t){const i=(0,d.toInt)(e.params.assetId);if(!(0,d.gt0)(i))return(0,l.sendServerToast)({response:t,toast:{text:"Missing assetId in request",type:"warning"},httpStatusCode:400});const r=m.AssetFile.ops().findOneBy({assetId:i,shown:1});return null==r?(p.info("Unknown assetId",e.originalUrl),this.repairAssetLaterAndSendPreview(i,e,t)):this.sendAssetFile(e,t,r)}async assetFileImg(e,t){const i=(0,d.toInt)(e.params.assetId);if(!(0,d.gt0)(i))return(0,l.send404Toast)({response:t,text:'Request was missing "assetId"',httpStatusCode:400});const r=(0,d.toInt)(e.params.assetFileId);if(!(0,d.gt0)(r))return(0,l.send404Toast)({response:t,text:'Request was missing "assetFileId"',httpStatusCode:400});const s=m.AssetFile.ops().findOneBy({id:r,assetId:i});return null==s?(0,l.send404Toast)({response:t,text:"Bad request: no such asset file "+r}):this.sendAssetFile(e,t,s)}async sendAssetFile(e,t,i){const r=i.assetId,s=await i.posixFile_(),n=e.path.split("/").includes("dl")||(0,o.truthyQuery)(e,"dl");if(null==s||await s.isEmpty())return n?(0,l.send404Toast)({response:t,text:"Asset file "+i.uri+" was missing"}):this.repairAssetLaterAndSendPreview(r,e,t);if(n)return p.info("Sending download",{assetId:r,af:i,nativePath:s.nativePath}),t.download(s.nativePath,s.base);const a=e.headers["user-agent"],d=await(0,u.prepFileForBrowser)({nativePath:s.nativePath,userAgent:a,...(0,h.pick)(i,"width","height","sha","mimetype","rotation","mimetype")});return null==d?(p.warn("cannot send file (null result from prepFileForBrowser)",{assetId:r,af:i}),g(r),(0,l.send404Toast)({response:t,text:`Failed to get browser-friendly preview for Asset ${r}.`,details:"I'll try to fix it."})):(p.info("sendAssetFile(): sending supported file: "+d),t.sendFile(d,(e=>(0,c.map)(e,(e=>p.warn("failed to send file",{error:e,assetId:r,af:i}))))))}async repairAssetLaterAndSendPreview(e,t,i){g(e);const r=await this.previews.ap(e).largestFileForReducer("fit");null!=r?i.sendFile(r.nativePath):(f.Asset.ops().upsertOne({id:e,shown:!1}),(0,l.send404Toast)({response:i,text:`Asset ${e} is missing preview images.`,details:"I'll try to fix it, but it will be hidden for now."}))}},t.requestAssetRepair=g},7523:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImgRouter=void 0;const s=r(i(66860)),n=i(49411),a=r(i(57441)),o=i(13779),l=i(7162),u=i(14889),c=i(91464),d=i(29731),h=i(77368),f=i(49441),m=i(43414),p=i(27446),g=i(19209),y=i(36297),v=i(9381),w=i(66776),b=i(75556),S=i(82798),P=i(89452),M=(0,l.mkLogger)("web.ImgRouter");t.ImgRouter=class{constructor(e){this.previews=e}router(){const e=(0,h.wrap)("ImgRouter",this.streamImage.bind(this));return s.default.Router().get("/img/:assetId/:reducer/:width",e)}async streamImage(e,t,i){const r=await this.getFileFromRequest(e,t);if(null!=r){if("setHeader"in t&&(0,b.gt)(r.width,500)){const e=P.AssetFile.dbl.pluckFirstf((e=>e.where({assetId:r.assetId,shown:1}).select("uri")))??"/asset-"+r.assetId+"."+r.file.ext,i=(0,w.map)(e,g.uriToBasename);if(M.debug("streamImage(): AssetFile URI",{shownUri:e,basename:i}),null!=i)try{t.setHeader("X-basename",(0,c.ensureSuffixIgnoreCase)(i,"."+r.file.ext))}catch(e){M.warn("streamImage(): setHeader error",{error:e})}else M.warn("streamImage(): failed to extract basename",{result:r})}return t.sendFile(r.file.nativePath)}}async getFileFromRequest(e,t){const i=e.params,r=(0,b.toInt)(i.assetId),s=v.ReducerNames.getCI(i.reducer)??"fit",l=(0,b.toInt)(i.width);if(null==r||null==s&&null==l)return M.warn("getFileFromRequest(): bad request",{assetId:r,reducer:s,width:l}),void t.sendStatus(y.HttpStatus.BadRequest);const h=this.previews.ap(r),g=h.fileForWidth(s,l);if(await g.exists())return{assetId:r,width:l,file:g};if(m.Settings.placeholderThumbs.valueOrDefault){const e=(0,d.stringShaToBuffer)((0,S.toS)(r)).toString("hex").slice(0,6),t=await(0,f.imageCacheDir_)();if(null==t)return;const i=t.join((0,c.splitEvery)(e,3).join(n.sep)+"-8w.png");return await i.applyIfEmpty_({fn_:t=>(0,a.default)({create:{width:8,height:8,channels:3,background:"#"+e}}).png().toFile(t.nativePath),timeoutMs:u.ShortCommandTimeoutMs}),{assetId:r,width:8,file:i}}const w=await h.widths(s)??[],P=await h.readInfo(),_=(0,p.isImageMimeType)(P?.mimetype)&&(0,p.isMimeTypeSupportedByBrowser)(P?.mimetype)?P?.width:void 0,T=(0,o.leastBy)([...w,_],(e=>(0,b.gt0)(e)&&Math.abs(l-e)));return null==T||T===l?(M.warn("Missing file, and no other widths found",{path:g.nativePath,assetId:r,reducer:s,requestedwidth:l,existingWidth:T}),void t.sendStatus(y.HttpStatus.NotFound)):T===_?(M.debug("redirecting to image actual",{assetId:r,reducer:s,width:l,f:g,existingWidth:T}),void t.redirect(["/img",r,"actual"].join("/"))):(M.debug("replacing requested width",{assetId:r,reducer:s,width:l,f:g,existingWidth:T}),void t.redirect(["/img",r,s,T].join("/")))}}},1807:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.siteManifest=t.ManifestRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(77368),l=i(22189),u=i(43586),c=i(43414),d=(0,n.lazy)((()=>(0,a.mkLogger)("web.ManifestRouter")));async function h({requestUri:e,id:t}){return{id:t??"com.photostructure",name:"PhotoStructure",start_url:e.with({path:c.Settings.defaultHomepagePath.valueOrDefault,query:null,fragment:null}).toString(),display:"fullscreen",icons:[{src:"/192.png",sizes:"192x192",type:"image/png"},{src:"/512.png",sizes:"512x512",type:"image/png"},{src:"/images/logo-gradient.svg",sizes:"any",type:"image/svg+xml"}],theme_color:"#845BAC",background_color:"#845BAC"}}t.ManifestRouter=class{router(){return s.default.Router().get("/site.webmanifest",(0,o.wrap)("SiteManifest",this.siteManifest.bind(this)))}async siteManifest(e,t,i){const r=await((0,u.LibraryUIDStore)()?.readUid_().catch((()=>{}))),s=(0,l.requestedUri)(e,{protocol:"http",host:c.Settings.hostname.value}),n=await h({id:r,requestUri:s});d().debug("siteManifest",n),t.type("application/manifest+json").json(n)}},t.siteManifest=h},81169:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAssetFileRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(72612),l=i(75556),u=i(89452),c=(0,n.mkLogger)("web.OpenAssetFileRouter");t.OpenAssetFileRouter=class{constructor(e){this.openFileService=e}router(){return s.default.Router().get("/api/openAssetFile/:assetFileId",(0,a.wrap)("OpenAssetFileRouter.assetFile",this.assetFile.bind(this)))}async assetFile(e,t){if(c.info("assetFile(): got request",{url:e.originalUrl,ip:e.ip}),!(0,o.isLocalhost)(e.ip))return c.info("Non-localhost request",{url:e.originalUrl,ip:e.ip}),t.sendStatus(400);const i=(0,l.toInt)(e.params.assetFileId);if(!(0,l.gt0)(i))return c.info("Missing assetFileId",e.originalUrl),t.sendStatus(400);const r=u.AssetFile.ops().findOneBy({id:i});if(null==r)return c.info("Invalid assetFileId",e.originalUrl),t.sendStatus(400);const s=await r.posixFile_();return null==s||await s.clear().notExists()?(c.info("File not found",{url:e.originalUrl,af:r,file:s}),t.sendStatus(400)):(c.info("Requesting openFileService("+s.nativePath+")...",{url:e.originalUrl,ip:e.ip}),this.openFileService(s.nativePath),t.sendStatus(204))}}},51706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PingRouter=void 0;const s=r(i(66860)),n=i(4691),a=i(36297);t.PingRouter=class{router(){return s.default.Router().get("/ping",((e,t)=>t.sendStatus((0,n.ending)()?a.HttpStatus.ServiceUnavailable:a.HttpStatus.OK)))}}},64104:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getPlansLicense=t.getPlansBilling=t.getPlansActivate=t.getPlansPick=t.PlansRouter=void 0;const s=r(i(66860)),n=i(4866),a=i(7162),o=i(2023),l=i(42041),u=i(77368),c=i(22189),d=i(13700),h=i(59714),f=i(43414),m=i(39938),p=i(88491),g=i(39784),y=(0,n.lazy)((()=>(0,a.mkLogger)("web.PlansRouter")));async function v(e,t){return await S({req:e,res:t,remotePath:"/plans/pick"})}async function w(e,t){return await S({req:e,res:t,remotePath:"/",params:{skipIndex:!0}})}async function b(e,t){return await S({req:e,res:t,remotePath:"/"})}async function S({req:e,res:t,remotePath:i,params:r={}}){const s=(0,c.requestedUri)(e).with({path:"/plans/license"}),n=await(0,d.sids)({timeoutMs:4*p.secondMs}),a=new URL("https://account.photostructure.com"+i);return a.searchParams.append("version",l.version),a.searchParams.append("uids",n.join(",")),(0,m.mapNotBlank)(f.Settings.coupon.value,(e=>a.searchParams.append("coupon",e))),a.searchParams.append("redirectToLibraryUrl",s.toString()),(0,o.mapEntries)(r,((e,t)=>a.searchParams.append(e,t))),y().info("GET /plans/pick",{redirectToLibraryUrl:s.toString()}),t.redirect(a.toString())}async function P(e,t){try{(0,m.mapNotBlankOr)(e.query.license,(async e=>{await(0,h.writeLicense)(e,3*p.secondMs),y().info("getPlansLicense(): Saved new license",e)}),(()=>{y().info("getPlansLicense(): no license in request",e.originalUrl)}))}catch(t){y().error("getPlansLicense(): Failed to save license",{err:t,url:e.originalUrl})}const i=(0,m.notBlankOr)((0,g.toA)(e.query.then)[0],"/settings");y().info("getPlansLicense(): redirecting to "+i),t.redirect(i)}t.PlansRouter=class{router(){return s.default.Router().get("/plans/pick",(0,u.wrap)("GET /plans/pick",v)).get("/plans/activate",(0,u.wrap)("GET /plans/activate",w)).get("/plans/billing",(0,u.wrap)("GET /plans/billing",b)).get("/plans/license",(0,u.wrap)("GET /plans/license",P))}},t.getPlansPick=v,t.getPlansActivate=w,t.getPlansBilling=b,t.getPlansLicense=P},79669:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressProvider=void 0;const r=i(5712),s=i(97742),n=i(24945),a=i(51498),o=i(4866),l=i(7162),u=i(46852),c=i(79403),d=i(51053),h=i(67220),f=i(11944),m=i(38625),p=i(88491),g=i(1429),y=i(21040),v=i(42313),w=i(82798),b=i(30690),S=i(89452),P=i(65548),M=(0,o.lazy)((()=>(0,l.mkLogger)("web.ProgressWithAssets")));t.ProgressProvider=class{constructor(e=10){this.maxLen=e,this.priorRecentAssets=new a.FifoCache(15,15*p.secondMs),this.testProgressStatesByVolume=new Map}async updates(){return(0,u.thenMap)(this.states(),(e=>({states:e})))}async states(){if((0,h.isPaused)())return[{volume:"โธ",state:"paused",hed:"Paused",dek:["Processing is paused. Resume via the navigation menu"+(d.isElectron?" or the system tray menu":"")+"."],recentAssetIds:[]}];const e=await c.HealthCheck.errorResults();if((0,f.isNotEmpty)(e))return M().warn("health check is failing",{errors:e}),[{volume:"โš ๏ธ",state:"paused",hed:"Health checks failed. Click for details.",dek:(0,f.uniq)((0,g.flatten)(e.map((e=>e.msg)))),recentAssetIds:[]}];const t=this.recentProgress();return M().debug("recentProgressWithAssets()",t),(0,f.isEmpty)(t)&&(0,m.isTrue)(s.env.TEST_PROGRESS)?this.testProgress():t}recentProgress(){const e=P.Progress.ops().allf((e=>e.where("updatedAt",">",Date.now()-p.minuteMs).whereNotNull("state").orderBy("volume")));(0,f.filterInPlace)(e,(e=>!(!(0,r.pidExists)(e.pid)&&"done"!==e.state&&(M().warn("Incomplete progress is from a dead process",{progress:e}),e.upsert({state:null}),1))));const t=[],i=new Set;for(const r of e){const e="done"===r.state,s=r.toSyncState(),n=this.priorRecentAssets.get((0,w.toS)(r.id))??[];if(!e){const e=((0,v.noRecentAssetIdsProgress)(s)?[]:S.AssetFile.recentAssetIdsByUriRoot((0,v.isRebuildProgress)(s)?void 0:s.uri,p.minuteMs,this.maxLen+i.size)).filter((e=>!i.has(e)&&!n.includes(e)));(0,f.isNotEmpty)(n)&&e.length>=this.maxLen&&e.splice(0,this.maxLen-1),n.unshift(...e),n.length=this.maxLen,this.priorRecentAssets.set((0,w.toS)(r.id),n);for(const e of n)i.add(e)}t.push({...s,recentAssetIds:n})}return t}async testAssetIds(e){const t=(0,y.getOrSet)(this.testProgressStatesByVolume,e,(()=>new n.BoundedList(this.maxLen))),i=b.Asset.dbl.pluckFirstf((e=>b.Asset.shownUnhidden(e).select("id").orderByRaw("random()").first()));return null!=i&&t.push(i),t.toA()}async testProgress(){const e=Math.round(Date.now()/(30*p.secondMs))%3,t=(d.isWin?["C:","D:","E:"]:["/","/home/bob/pictures","/mnt/nas"])[e];return[{volume:t,state:"processing",hed:"Processing, about 32 minutes remaining",dek:["Processing C:\\Users\\mrm\\Pictures\\20161214-pixel\\DCIM\\Camera\\IMG_20160903_090736.jpg","Processed 445 images and videos. 1,386 remain to be processed."],completePct:40,incompletePct:25,scanningPct:35,recentAssetIds:await this.testAssetIds(t)}]}}},47458:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.render=void 0;const r=i(9678),s=i(4866),n=i(7162),a=i(19658),o=i(69060),l=i(72612),u=i(15203),c=i(51053),d=i(43414),h=i(67220),f=i(38625),m=i(20636),p=i(39607),g=i(50725),y=(0,s.lazy)((()=>(0,n.mkLogger)("web.PugHelpers")));t.render=async function(e,t,i,s={}){const n=e.headers["user-agent"];t.setHeader("Feature-Policy","autoplay 'self'");const v=[],w=!0===n?.toLowerCase().includes("electron")&&(0,l.isLocalhost)(e.ip)||(0,f.isTrue)(e.query.electron);w&&(v.push("electron"),c.isMac?v.push("mac"):c.isWin?v.push("win"):c.isLinux&&v.push("linux")),a.isDev&&v.push("is-dev"),(0,p.isChrome)(n)?v.push("chrome"):(0,p.isSafari)(n)?v.push("safari"):(0,p.isFirefox)(n)&&v.push("firefox"),(0,p.isIphone)(n)?v.push("iphone"):(0,p.isIpad)(n)&&v.push("ipad"),(0,h.isPaused)()&&v.push("is-paused"),(0,l.isLocalhost)(e.ip)&&!(0,u.isDocker)()&&v.push("is-localhost");try{!0===await(0,m.thenOrTimeout)((0,o.p)(),250)&&v.push("is-plus")}catch{}d.Settings.enableArchive.valueOrDefault&&v.push("enable-archive"),d.Settings.enableDelete.valueOrDefault&&v.push("enable-delete"),d.Settings.enableRemove.valueOrDefault&&v.push("enable-remove");const b={bodyClass:v.join(" "),isDocker:(0,u.isDocker)(),isElectron:w,isDev:a.isDev,nonce:t.locals.cspNonce,hasEmail:d.Settings.email.hasValue(),...s};y().debug("render()",{ua:n,template:i,options:b,headers:e.headers}),t.render(i,{rootTags:null==g.Tag.db()?void 0:g.Tag.roots(),title:(0,r.AppName)(),...b})}},69475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SSEHealthRouter=void 0;const r=i(34996),s=i(41749),n=i(79403),a=i(232),o={event:"done",data:{done:!0}};function l(e){return null==e?void 0:{event:"result",data:e}}class u extends s.ServerSentEventsRouter{constructor(){super("/sse/health")}firstEvents(e,t){return this.sendResults(t),[]}async sendResults(e){const t=[],i=[];i.push(n.HealthCheck.summary());for(const e of n.HealthCheck.all()){const r=e.toResultSync();i.push(r),("pending"===r.level||e.isStale())&&t.push(e)}e.write((0,a.mkEventStream)(...i.map(l))),this.logger.debug("sendResults (sync)",{pending:t.map((e=>e.id)),resolved:i.map((e=>e.id))});for await(const i of r.Deferred.toAsyncIterable(t.map((e=>e.result())))){const t=(0,a.mkEventStream)(l(i),l(n.HealthCheck.summary()));this.logger.debug("sendResults (async)",{result:i,chunk:t}),e.write(t)}e.write((0,a.mkEventStream)(l(n.HealthCheck.summary()),o),(()=>this.endStream(e)))}}t.SSEHealthRouter=u},35818:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsRouter=void 0;const s=r(i(66860)),n=i(42748),a=i(49411),o=i(7162),l=i(19658),u=i(38307),c=i(82341),d=i(18226),h=i(79015),f=i(77368),m=i(98462),p=i(46517),g=i(69060),y=i(15203),v=i(51053),w=i(83773),b=i(43414),S=i(82041),P=i(57310),M=i(11944),_=i(39938),T=i(38625),E=i(88491),D=i(19067),k=i(87748),x=i(66776),C=i(61570),F=i(20636),I=i(17078),A=i(39784),O=i(82798),L=i(37831),R=i(4958),N=i(47458),B=(0,o.mkLogger)("web.SettingsRouter");t.SettingsRouter=class{constructor(e=c.libraryDirPosixFile,t=L.librarySettings,i=R.suggestedLibraryDirs){this.libraryDir=e,this.settings=t,this.libraryDirSuggester=i}router(){return s.default.Router().get("/setting",((e,t)=>t.redirect("/settings"))).get("/settings",(0,f.wrap)("GET /settings",this.get.bind(this))).post("/settings",(0,f.wrap)("POST /settings",this.post.bind(this)))}async get(e,t){const{err:i,libraryDir:r}=e.body;try{await(0,S.readSettings)();const s=await(0,F.thenOrTimeoutError)(this.requestSettings(e),1e3);return await(0,F.thenOrTimeoutError)(this.renderSettings(e,t,s,r,i),1e3)}catch(e){return B.warn("requestSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}}async renderSettings(e,t,i,r,s){(0,h.ee)().emit("clearCache");let o=await this.libraryDirSuggester();if(null==(0,O.toS)(s).match(/choose a different directory/i)){const e=await R.SuggestedLibraryDir.for(r);null!=e&&o.unshift(e)}(0,M.isEmpty)(o)&&(o=void 0);const u=this.libraryDir();(0,_.blank)(s)&&(0,y.isDocker)()&&(null==u||await u.isNotDirectory())&&(s=`PS_LIBRARY_DIR, ${u?.nativePath??"/ps/library"}, doesn't exist: please add it as a bind mount.`);const c=await(0,p.getVideoToolDetails_)(l.isProd?void 0:e.query),C=await(0,d.picturesDir)(),F=await(0,g.b)(),A={err:s,...i,autoUpdateCheck:i.autoUpdateCheck??!0,allowUserAgent:i.allowUserAgent??!0,reportErrors:i.reportErrors??!0,welcome:(0,x.mapOr)(l.isProd?void 0:e.query.welcome,T.isTrue,(()=>!(0,S.libraryHasSettings)())),title:null==u?"Welcome!":"Settings",videoToolDetails:c,picturesPath:C,jsonScanPaths:(0,x.map)(b.Settings.scanPaths.value,k.stringify),delimiter:a.delimiter,exampleScanPath:[C,v.isWin?"D:\\PHOTOS":v.isMac?"/Volumes/External HD/Pictures":"/mnt/nas/homes/photos"].join(a.delimiter),currentLibraryDir:(0,x.map)(u,(e=>e.nativePath)),minFreeAvailable:(0,I.fmtBytes)(b.Settings.minDiskFreeGb.valueOrDefault*I.GB),suggestedLibraryDirs:o,samplePath:(0,w.pathToLibraryAsset)(n.DateTime.now(),m.BaseFile.for("photo.jpg")).join(a.sep),subTier:await(0,g.t)(),subTrial:(0,T.isTrue)(F?.l?.trial),subEmail:F?.l?.sub,subExpiresInDuration:(0,x.map)(F?.l?.exp,(e=>(0,D.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,x.map)(F?.l?.exp,E.fmtIsoDate),userAgent:await(0,P.systemUserAgent)()};B.info("rendering settings",A),(0,f.disableCache)(t),await(0,N.render)(e,t,"settings",A)}async post(e,t){const i=e.body,r=(0,_.toNotBlank)("libraryDirCustom"===i.libraryDirRadio?i.libraryDir:i.libraryDirRadio),s=i=>this.renderSettings(e,t,c,r,i),n=r??b.Settings.libraryDir.valueOrDefault;if((0,_.blank)(n))return s("Please choose a directory for your library.");const o=(0,a.resolve)(n),c=await this.requestSettings(e);B.info("POST",{libraryDir:o,settings:c,body:i}),l.isTest&&(0,u.stdoutWrite)({post:i,settings:c,method:e.method,libraryDir:o});try{const e=await(0,L.saveLibrarySettings)(o,c);if("error"in e)return B.info("error saving library settings",{result:e}),s(e.error);B.info("saved library settings. Waiting for bookkeeping to finish...",e),await e.ready,B.info("ready. Redirecting to /splash...",e)}catch(e){return s(e)}return t.redirect("/splash")}async requestSettings(e){const{scan:t,scanPath:i,copyAssets:r,autoUpdateCheck:s,allowUserAgent:n,reportErrors:a}=e.body,o=this.settings();return(0,_.notBlank)(t)&&(o.scanAllDrives="scanAllDrives"===t,o.scanPath=(0,M.compactBlanks)((0,A.toA)(i))),(0,_.notBlank)(r)&&(o.copyAssets="copyEnabled"===r),o.allowUserAgent=(0,T.toBoolean)(n),o.autoUpdateCheck=(0,T.toBoolean)(s),o.reportErrors=(0,T.toBoolean)(a),B.info("requestSettings()",{req_body:(0,C.pick)(e.body,"scan","scanPath","copyAssets","autoUpdateCheck","allowUserAgent","reportErrors"),result:o}),(0,L.librarySettings)(o)}}},71885:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SpaRouter=void 0;const s=r(i(66860)),n=i(77368),a=i(22189),o=i(16715),l=i(47458);t.SpaRouter=class{router(){const e=(0,n.wrap)("SpaRouter",this.get.bind(this));return s.default.Router().get("/tag*",e).get("/asset/:assetId",(0,n.wrap)("SpaRouter.Asset",this.getAsset.bind(this))).get("/search",e)}async getAsset(e,t,i){const r=await(0,o.getAssetOpenGraph)((0,a.requestedUri)(e),e.params.assetId);return(0,l.render)(e,t,"app",null==r?{}:{meta:r})}get(e,t,i){if(!e.path?.startsWith("/tag")||null!=(0,n.getSeedOrRedirect)(e,t))return(0,l.render)(e,t,"app",{})}}},39787:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(11944),l=i(66776),u=i(75556),c=i(89452),d=(0,n.mkLogger)("web.VideoRouter");t.VideoRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/video/:assetId",(0,a.wrap)("VideoRouter",this.videoImage.bind(this)))}async videoImage(e,t,i){const r=e.params,s=(0,u.toInt)(r.assetId);if(!(0,u.gt0)(s))return d.warn("Malformed request (missing assetId)",{params:e.params}),t.sendStatus(400);const n=this.previews.ap(s).mp4();if(await n.exists())return d.info("streaming transcoded video",n),t.sendFile(n.nativePath);const a=c.AssetFile.ops().findBy({assetId:s,shown:1});if((0,o.isEmpty)(a))return d.warn("Malformed request (bad assetId)",{params:e.params}),t.sendStatus(400);const h=a[0],f=await(0,l.map)(h,(e=>e.posixFile_()));return null!=f&&h.isVideo&&await f.exists()?t.sendFile(f.nativePath):(d.warn("Shown assetFile isn't a video",h),t.sendStatus(400))}}},21625:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebService=void 0;const s=r(i(66860)),n=r(i(47806)),a=r(i(6005)),o=r(i(97742)),l=i(4866),u=i(7162),c=i(70283),d=i(38307),h=i(4691),f=i(2126),m=i(46852),p=i(53525),g=i(79141),y=i(28941),v=i(53235),w=i(77659),b=i(22189),S=i(9786),P=i(50080),M=i(1597),_=i(98250),T=i(27175),E=i(57294),D=i(79403),k=i(13700),x=i(38786),C=i(94845),F=i(43414),I=i(82041),A=i(53719),O=i(46573),L=i(17679),R=i(36297),N=i(29144),B=i(43947),j=i(66776),z=i(61715),V=i(23022),W=i(48652),U=i(49374),q=i(27242),H=i(27579),G=i(20990),$=i(39946),J=i(36389),K=i(86840),Y=i(16654),X=i(47576),Z=i(6757),Q=i(40687),ee=i(34312),te=i(47967),ie=i(28631),re=i(23163),se=i(7523),ne=i(1807),ae=i(81169),oe=i(51706),le=i(64104),ue=i(79669),ce=i(69475),de=i(35818),he=i(71885),fe=i(39787),me=i(26518),pe=i(63986);function ge(e,t){t.endsWith(".js")&&e.setHeader("Content-Type","application/javascript")}const ye=(0,u.mkLogger)("web.WebService"),ve=e=>(0,E.showFileInFolder)(_.PosixFile.for(e));t.WebService=class{constructor(){this.setup=(0,l.lazy)((async()=>{if(ye.debug("setup(): started"),o.default.on("SIGPIPE",(e=>{ye.info("Caught SIGPIPE",e)})),F.Settings.libraryDir.watchLater((()=>Me.unset())),await(0,m.rejected)(this.service.ready))return void ye.error("setup(): failed, service.ready was rejected");await(0,N.setupShimDelegates)();const e=this.app;if(e.use((new w.RequestLogger).router),e.use(((e,t,i)=>{t.locals.cspNonce=a.default.randomBytes(16).toString("hex"),i()})),F.Settings.trustProxy.hasValue()){const t=F.Settings.trustProxy.value,i="true"===t||"false"!==t&&(0,c.mapGte0Or)(t,(e=>e),t);e.set("trust proxy",i),ye.info("trust proxy set",{value:i})}if(e.use(P.expressErrorHandlerWithToast),(0,q.sentryEnabled)())try{e.use(i(9856).Handlers.requestHandler())}catch(e){ye.warn("Failed to initialize Sentry requestHandler",{error:e})}if(F.Settings.disabledHelmetMiddleware.valueOrDefault.includes(L.HelmetPlugins.all))ye.warn("DANGER: disabledHelmetMiddleware includes 'all': not enabling any Helmet middleware.");else{F.Settings.disabledHelmetMiddleware.valueOrDefault.includes(L.HelmetPlugins.contentSecurityPolicy)||e.use(ie.cspHandler);const t={contentSecurityPolicy:!1};for(const e of F.Settings.disabledHelmetMiddleware.valueOrDefault.filter((e=>e!==L.HelmetPlugins.all)))t[e]=!1;e.use((0,n.default)(t))}e.use(b.addXSettingsHandler),e.use(pe.json()),e.use(pe.urlencoded({extended:!1}));const t=T.ProjectPath.Public(),r=T.ProjectPath.Views();if(ye.info("setup()",{libraryDir:F.Settings.libraryDir.valueOrDefault,publicRoot:t,viewsRoot:r}),I.libraryHasSettings.watch((()=>e.set("etag",(0,I.libraryHasSettings)()))),e.set("views",r),e.set("view engine","pug"),e.use((new oe.PingRouter).router()),e.use((new y.ApiHealthRouter).router()),e.use((0,M.viewRouter)({path:"/splash",view:"splash"})),e.use((new Q.ApiSplashRouter).router()),e.use((0,M.viewRouter)({path:"/health",view:"health"})),e.use((new ce.SSEHealthRouter).router()),e.use((new K.AdminPostRouter).router()),e.get("/status",((e,t)=>t.redirect("/health"))),e.use(await(0,S.serveStaticGz)(t)),e.use(s.default.static(t,{setHeaders:ge})),e.use((new J.AboutRouter).router()),e.use((new me.WelcomeRouter).router()),e.use((new le.PlansRouter).router()),e.use(Pe()),(0,C.isPacked)()||(e.use("/die",((e,t)=>{ye.info("/die was requested",{url:e.originalUrl}),t.sendStatus(R.HttpStatus.Accepted),(0,f.exit)({reason:"/die",status:1})})),e.use("/test-sentry",((e,t)=>{(0,H.sendToSentry)(new g.WrappedError("test message sent to sentry at "+new Date)),t.sendStatus(R.HttpStatus.Accepted)}))),e.use(((e,t,i)=>(0,h.ending)()?(ye.info("ending(): returning 500",{requestUri:(0,b.requestedUri)(e)}),t.sendStatus(500)):function(){const e=D.HealthCheck.runState();switch(e){case z.RunStates.loading:return we();case z.RunStates.welcome:return Se();case z.RunStates.ready:return Me()??Me.refresh()??be();case z.RunStates.failed:return be();default:throw new V.UnreachableCaseError(e)}}()(e,t,i))),(0,q.sentryEnabled)())try{e.use(i(9856).Handlers.errorHandler())}catch(e){ye.warn("Failed to initialize Sentry error handling",{error:e})}const l=F.Settings.httpPort.valueOrDefault,u=F.Settings.exposeNetworkWithoutAuth.valueOrDefault,v=U.Library.instance();null!=v?D.HealthCheck.addLoadingMsg("Loading library..."):D.HealthCheck.addLoadingMsg("Starting...");const _=async()=>{ye.info("setup(): http server callback",{httpPort:l,expose:u});const e=[F.Settings.httpPort];null!=v&&e.push(F.Settings.libraryDir),(0,d.stdoutWriteSettings)(...e),null==v?((0,k.sids)((0,A.commandTimeoutMs)()).catch((e=>ye.warn("failed to prefetch sids",e))),(0,O.volumes)().catch((e=>ye.warn("failed to prefetch volumes",e)))):(await v.ready,Me.unset()),await(0,$.libraryHealthCheckSetup)(),await D.HealthCheck.awaitSettled(),null!=v&&d.StdoutWrite.restartSync()},E=u?e.listen(l,_):e.listen(l,F.Settings.localhost.valueOrDefault,_);return E.on("error",(e=>{ye.warn("http.server.onError()",e),"EADDRINUSE"===e.code&&(0,f.exit)({reason:"Port "+l+" is already in use: is PhotoStructure already running?"+p.FatalErrorFlag+p.DoNotSendErrorFlag+p.WebFatalErrorFlag,error:e,status:3})})),new x.EndableServer("http.WebService",E)})),this.app=(0,s.default)(),this.service=new G.Service({name:"web"}),this.setup()}};const we=(0,l.lazy)((()=>(0,v.redirectRouter)("/splash"))),be=(0,l.lazy)((()=>(0,v.redirectRouter)("/health"))),Se=(0,l.lazy)((()=>(0,v.redirectRouter)("/welcome"))),Pe=(0,l.lazy)((()=>(new de.SettingsRouter).router())),Me=(0,l.lazy)((()=>{const e=U.Library.instance();if(null==e)return ye.warn("libraryRouter invoked before library is set up."),void setImmediate((()=>Me.unset()));ye.info("Setting up library router for "+(0,j.map)(e,(e=>e.rootDir)));const t=e.previews(),i=new ue.ProgressProvider,r=s.default.Router();return r.use((new ne.ManifestRouter).router()),r.use(new ee.ApiSystemRouter(ve).router()),r.use((new te.ApiTagRouter).router()),r.use(new Y.ApiAssetRouter(t).router()),r.use((new Z.ApiSearchRouter).router()),r.use((new he.SpaRouter).router()),r.use(new ae.OpenAssetFileRouter(ve).router()),r.use(new re.ImgActualRouter(t).router()),r.use(new se.ImgRouter(t).router()),r.use(new fe.VideoRouter(t).router()),r.use(new X.ProgressRouter(i).router()),r.use("/",((e,t)=>{ye.debug("in root route",{res_headersSent:t.headersSent,res_headers:t.getHeaders()}),t.redirect(302,(0,W.mkHomeFullPath)(e.query))})),r}));(0,B.later)((()=>{F.Settings.libraryDir.watchLater((()=>Me.unset()))}))},26518:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WelcomeRouter=void 0;const s=r(i(66860)),n=i(7162),a=i(77368),o=i(79403),l=i(69060),u=i(43414),c=i(36297),d=i(4958),h=i(64104),f=i(47458);t.WelcomeRouter=class{constructor(){this.logger=(0,n.mkLogger)("WelcomeRouter")}router(){return s.default.Router().get("/welcome",(0,a.wrap)("GET /welcome",this.get.bind(this))).post("/welcome",(0,a.wrap)("POST /welcome",this.post.bind(this)))}async get(e,t){return"welcome"!==o.HealthCheck.runState()?t.redirect(c.HttpStatus.Found,"/"):((0,d.suggestedLibraryDirs)(),(0,f.render)(e,t,"welcome",{}))}async post(e,t){return!u.Settings.pickPlanOnWelcome.valueOrDefault||await(0,l.p)()?t.redirect("/settings"):(0,h.getPlansPick)(e,t)}}},81627:e=>{"use strict";e.exports=require("@iarna/toml")},1487:e=>{"use strict";e.exports=require("@parcel/watcher")},9160:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},9856:e=>{"use strict";e.exports=require("@sentry/node")},39084:e=>{"use strict";e.exports=require("assert")},52167:e=>{"use strict";e.exports=require("axios")},5712:e=>{"use strict";e.exports=require("batch-cluster")},85890:e=>{"use strict";e.exports=require("better-sqlite3")},63986:e=>{"use strict";e.exports=require("body-parser")},7304:e=>{"use strict";e.exports=require("commander")},71239:e=>{"use strict";e.exports=require("events")},889:e=>{"use strict";e.exports=require("exiftool-vendored")},66860:e=>{"use strict";e.exports=require("express")},25861:e=>{"use strict";e.exports=require("fast-xml-parser")},53221:e=>{"use strict";e.exports=require("file-type")},44470:e=>{"use strict";e.exports=require("fs-extra")},1604:e=>{"use strict";e.exports=require("he")},47806:e=>{"use strict";e.exports=require("helmet")},40514:e=>{"use strict";e.exports=require("knex")},42748:e=>{"use strict";e.exports=require("luxon")},89965:e=>{"use strict";e.exports=require("ml-kmeans")},34235:e=>{"use strict";e.exports=require("moo")},50764:e=>{"use strict";e.exports=require("nearley")},57153:e=>{"use strict";e.exports=require("papaparse")},78932:e=>{"use strict";e.exports=require("picomatch")},82264:e=>{"use strict";e.exports=require("platform-folders")},55543:e=>{"use strict";e.exports=require("plist")},39369:e=>{"use strict";e.exports=require("process")},46850:e=>{"use strict";e.exports=require("punycode")},10912:e=>{"use strict";e.exports=require("semver")},57441:e=>{"use strict";e.exports=require("sharp")},34261:e=>{"use strict";e.exports=require("source-map-support")},41313:e=>{"use strict";e.exports=require("trash")},83965:e=>{"use strict";e.exports=require("type-detect")},16464:e=>{"use strict";e.exports=require("util")},35740:e=>{"use strict";e.exports=require("util/types")},35001:e=>{"use strict";e.exports=require("cluster")},6113:e=>{"use strict";e.exports=require("crypto")},17718:e=>{"use strict";e.exports=require("node:child_process")},6005:e=>{"use strict";e.exports=require("node:crypto")},30604:e=>{"use strict";e.exports=require("node:dns")},87561:e=>{"use strict";e.exports=require("node:fs")},93977:e=>{"use strict";e.exports=require("node:fs/promises")},87503:e=>{"use strict";e.exports=require("node:net")},70612:e=>{"use strict";e.exports=require("node:os")},49411:e=>{"use strict";e.exports=require("node:path")},90410:e=>{"use strict";e.exports=require("node:path/posix")},97742:e=>{"use strict";e.exports=require("node:process")},84492:e=>{"use strict";e.exports=require("node:stream")},76402:e=>{"use strict";e.exports=require("node:stream/promises")},92332:e=>{"use strict";e.exports=require("node:timers")},47261:e=>{"use strict";e.exports=require("node:util")},65628:e=>{"use strict";e.exports=require("node:zlib")},71017:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=72316);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/worker.js b/bin/worker.js index 3e07a95..b7474dd 100755 --- a/bin/worker.js +++ b/bin/worker.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return x(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return x(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function x(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),x=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,x.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,x.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,a.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():x()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function x(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=x,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const n=i(97742),r=i(75556),s=i(17078),a=i(6667);function o(){const e=(0,n.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,n.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function x(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=x;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(x())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),x=i(46027),E=i(4586),T=i(17875),D=i(98462),k=i(25015),C=i(3955),F=i(51053),O=i(71663),I=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))I().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return I().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){I().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){I().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!A(n,u)){I().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(I().info("killOldProcs(): killing",{reason:d,json:n}),a.push(N(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),I().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void I().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{I().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,x.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const n=i(9678),r=i(7162),s=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?n.SimpleShortAppName:n.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),S=i(46852),b=i(69317),P=i(9288),M=i(51053),_=i(71663),x=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?O:N)).filter((e=>E(e)&&t.includes(e.pid)));return x().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return R(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],I))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function O(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const I={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,I),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,b.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...I,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>x.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const x=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||x().has(e))return;x().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=n.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let o;const l=async i=>{const n=Date.now(),r=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const x=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=x.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function x(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=x,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:x(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const n=i(4866),r=i(66776),s=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,n.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function S(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function b(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):S(t)}async function P(e){const[i,n,r,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...n,...r,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=S,t.assetFileImageHashFields_=b,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const n=i.capturedAt.toAssetFileFields();return null==n?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...n,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),b(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),S=i(19209),b=(0,n.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function x(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=x;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function T(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function D(e){const t=S.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const n=P.indexOf(t.scheme);if(null==n)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:n,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:x(r),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return b().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=T,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of T(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return b().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return b().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const n=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,n.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),x=i(26588),E=i(46234),T=i(21669),D=i(7162),k=i(49379),C=i(49273),F="TIMEOUT",O=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===F)return void O().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,x.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,x.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,r=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===n&&h(this,a,i,"f"),d(this,o,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function x({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=x,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await x({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await x({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await x({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await x({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,o.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,f.childProcLocale)():{},...E(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),x=i(49379),E=i(79141),T=i(83837),D=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function O(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function I(e,i,n,r=0){const a=new Date,o=[];return(0,b.niceable)(i,n)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&O(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(a.stdin);const S=new d.Latch;null==a.stdout?S.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==a.stderr||r?b.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??x.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=O,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},24905:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},95298:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),x=i(79141),E=i(45512),T=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new x.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return a.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},75862:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const n=i(4866),r=i(11944),s=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,n.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const n=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:n,closeLabhashes:[n],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function S(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,n.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return S((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=S;const b=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(b,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const n=(0,c.unlabhash)(e),s=S(n);return null!=n&&null!=s&&((0,r.pushUniq)(s.closeLabhashes,e),(0,r.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(n))),s})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const n=i(4866),r=i(11944),s=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(x(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],n=[];for(let r=0;re>b?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-n)])}function _(e){const[t,i,n]=v(e),r=(t+16)/116,s=i/500+r,a=r-n/200,o=s*s*s,l=a*a*a,u=o>b?o:(116*s-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>b?l:(116*a-16)/P;return[u*S.X,c*S.Y,d*S.Z]}function x(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=x,t.LabBitZip=(0,n.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const T=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,n]=(0,f.clampRGB)(e),r=Math.max(t,i,n),s=r-Math.min(t,i,n),a=s?r===t?(i-n)/s:r===i?2+(n-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),r?s/r*100:0,r/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,n]=e,r=(200-i)*n/100;return[t,r>0&&r<200?i*n/100/(r<=100?r:200-r)*100:0,r/2]}function O(e){const[t,i,n]=e,r=i*(n<50?n:100-n)/100;return[t,r>0?2*r/(n+r)*100:0,n+r]}function I(e){const t=e[0]/360*6,i=e[1]/100,n=e[2]/100,r=Math.floor(t),s=n*(1-i),a=n*(1-(t-r)*i),o=n*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[n,a,s,s,o,n][l],255*[o,n,n,a,s,s][l],255*[s,s,o,n,n,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(T,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(O(e))},t.hsv2hsl=F,t.hsl2hsv=O,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const n=i(75556),r=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,n,s]=e,[a,o,l]=t,u=i-a,c=n-o,d=s-l,h=(0,r.sqrt)(n**2+s**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,n.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,n,l]=e,u=(0,r.sqrt)(n**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=n*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let S=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);S+=2*(S<0?1:0)*Math.PI;const b=c-i,P=v-y;let M=y*v==0?0:S-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),x=(i+c)/2,E=(y+v)/2;let T;y*v==0?T=w+S:(T=(w+S)/2,T-=(Math.abs(w-S)>Math.PI?1:0)*Math.PI,T+=2*(T<0?1:0)*Math.PI);const D=(x-50)**2,k=1-.17*Math.cos(T-Math.PI/6)+.24*Math.cos(2*T)+.32*Math.cos(3*T+Math.PI/30)-.2*Math.cos(4*T-63*Math.PI/180),C=1+.015*D/(0,r.sqrt)(20+D),F=1+.045*E,O=1+.015*E*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*T-275)/25)**2),L=2*(0,r.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),A=-1*Math.sin(2*I)*L;return(0,r.sqrt)(Math.pow(b/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*O),2)+A*P/(a*F)*_/(o*O))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const n=i(11944),r=i(75556),s=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,n.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,n.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const n=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=n&&(0,r.gt0)(i)?new c(n,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},17566:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),S=i(65976),b=i(53682),P=(0,n.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=b.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=b.ModeCount){const i=Date.now(),n=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,n=4*t;g=Math.round(Math.max(i,Math.min(n,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,n).map((e=>{const n=(0,p.kmeans)(f,g,{...x,seed:e}),r=k(n.centroids,f.length);if(r.lengtht&&D(g-1);const s=r.slice(0,t),o=function(e){const t=new m.Average;for(const[i,n]of a.entries()){const r=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=s&&(0,l.times)(n,(()=>t.push(s.value)))}return t.p84}(s);return{...n,centroids:s,description:{kIn:g,kOut:n.centroids.length,kMerged:r.length,score:o,iterations:n.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:n}),T(a,t);const O=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>S.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:O,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,S.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:O,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const n of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,n)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,n))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},x=(0,n.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:n=3}){if(n<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:n,pixelCount:e.length,filteredCount:s.length}),E({labs:e,minK:t,thresh:.75*r,retries:n-1}))}function T(e,t){const i=e.countSum,n=e.size;D(e);const s=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>S.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:n,mergedColors:s,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[n,r]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(n),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:n}):(e.delete(n),e.incr(a.labhash,r))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const n=[];for(const t of e){const e=n.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?n.push(t):e.size+=t.size}const r=t/100;return(0,s.sortBy)(n.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{x.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=T,t.mergeLabhashes=D,t.mergeNearCentroids=k},64932:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,n.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,n=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),n.push(e[2])}const r=(i.stdDev??0)+(n.stdDev??0),s=r{Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const n=i(75556),r=i(61570),s=i(84253);t.isModeData=function(e){return(0,n.gt0)(e.mode0)&&(0,n.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const n=i(75556),r=i(65113),s=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,n.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,n.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function x(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function T(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=x(e),n=E(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=x,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):T(e)},t.datedToDateTime=T,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),x=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class T{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new T(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=T,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${E(s)}:${E(a)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):D(e,(0,x.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function O(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new T(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function I(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,x.hasZone)(t)?C:k):void 0},t.datedToYMD=F,t.toFuzzyDate=O,t.sameDay=function(e,t){return(0,c.lte)(I(e,t),l.dayMs)},t.diffMillis=I,t.closeTo=function(e,t,i){return(0,u.mapOr)(I(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(n+1),l=(0,x.getZoneName)(e),u=l===(0,x.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?O(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,x.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,x.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),x=i(45161),E=i(50140),T=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,T.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function O(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>O(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=I;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;x.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return x.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),a=i(36218),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,x=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,T=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),x,T,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const O=/\b(?(?:Etc\/)?GMT)\b/,I=(0,s.lazy)((()=>(0,m.concatRegexp)([O,x,D,m.RegExpOptional.from(k)])));function L(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),x=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const T=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===T)return T;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return x().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function O(e){return(0,h.within)(k(),C(),e)}function I(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return O(e)&&(!(0,u.gt0)(t)||I(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),F.unset()}))})),t.validYear=O,t.validMonth=I,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),x=i(51510),E=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,o.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:b.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),a=i(43414);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function x(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await x(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=x},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const n=i(53525);class r extends Error{constructor(e){super(e+n.InternalErrorFlag)}}t.InternalError=r},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function a(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),x=i(88491),E=i(43383),T=i(24603),D=i(16475),k=i(1429),C=i(87748),F=i(21040),O=i(66776),I=i(75556),L=i(61570),A=i(20636),R=i(39784),N=i(7162),B=i(70283),z=i(55568),j=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Z=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,I.gt)(i,V.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,I.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=x.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,z.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),x.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,I.gt)((0,H.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,z.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},r=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,z.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*x.secondMs);await(0,Z.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:j.ShortCommandTimeoutMs,intervalMs:x.secondMs}),p(this,o,"f").destroy(),(0,O.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,z.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,z.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,O.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,O.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),x=i(39938),E=i(88491),T=i(24603),D=i(1429),k=i(87748),C=i(66776),F=i(75556),O=i(61570),I=i(98510),L=i(65113),A=i(44726),R=i(39784),N=i(82798),B=i(13779),z=i(34996),j=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Z=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,j.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,x.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,j.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,j.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,j.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,R.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(x.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,j.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,j.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,j.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,j.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,j.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,j.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,j.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,j.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,j.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,j.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,j.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,j.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,j.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,j.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,j.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,j.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,j.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,j.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,j.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,O.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new z.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,j.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,F.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new z.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*E.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),a=i(3955);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),S=i(2023),b=i(46852),P=i(4586),M=i(10156),_=i(85943),x=i(82341),E=i(20902),T=i(9483),D=i(51053),k=i(38336),C=i(51776),F=i(43414),O=i(77390),I=i(98462),L=i(64546),A=i(28659),R=i(1391),N=i(69716),B=i(95725),z=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),j=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=j.get(t);if(null!=i)return i;const n=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),r=V.test(t)||n.isDirectorySync(),s=(0,R.native2posix)(n.nativePath),a=r?(0,m.ensureSuffix)(s,"/"):s;return j.set(t,a),j.set(a,a),j.set(n.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(n.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),z().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,z().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,S.pairToObject)(this.reason,a(this,n,"m",r).bind(this)):{}}}n=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return z().tap({msg:"apply()",level:i?T.LogLevels.debug:T.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){z().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):z().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,n){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new U(`**/${t}/${r[0]}/`,n)),r.length>1&&e.push(new U(`**/${t}/(${r.join("|")})/`,n))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const n=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",n,"Linux /var"),t("mnt",n,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:ne,notInHiddenPhotoStructureDir:ae,notNoMedia:re,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&z().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):z().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const n=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,s]=(0,g.partition)(n,(e=>e.pattern.endsWith("/")));return{dir:r,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Y=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().dir}async function ie(e){return k.Predicates.whyRejected(e,...te(e))}function ne(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,b.thenNot)((0,A.hasNoMedia)(e))}function se(e){return(0,b.thenNot)((0,L.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,x.libraryDirPosixFile)(),(0,x.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return z().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,O.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),x=i(11944),E=i(37609),T=i(88491),D=i(24603),k=i(19067),C=i(66776),F=i(75556),O=i(23175),I=i(20636),L=i(82798),A=i(19658),R=i(1058),N=i(55568),B=i(91641),z=i(95557),j=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,x.compactBlanks)([H.TokenRadix.encode(w(this,r,"f",s)),N.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,q.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,O.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,x.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,j.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,I.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),a=i(95725);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),x=i(17354),E=i(79015),T=i(3955),D=i(8177),k=i(43414),C=i(91464),F=i(37086),O=i(59873),I=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,I.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,F.uid)(),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",o).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,x.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",o).call(this):!a&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,I.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,O.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),a=i(76402),o=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const n=await Promise.race([x(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function x(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return x((0,y.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function E(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=E,t.grandParentBasename=function(e){return E(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),F([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),F([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function x(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...x(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),x=i(75556),E=i(61570),T=i(20636),D=i(49049),k=i(17078),C=i(82798),F=i(13779),O=i(7162),I=i(14889),L=i(91464),A=i(46852),R=i(7383),N=i(21142),B=i(69317),z=i(14195),j=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Z=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,O.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,z.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,z.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,x.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,x.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,x.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),S=i(64067),b=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function x(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function T(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,b.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function O(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,S.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:O}]}function L(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:x},{notRejectedRating:T},{notExcludedKeyword:D}]}async function A(e,t){return await u.Predicates.whyRejected(e,...t??L(e))??await(0,S.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,n.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=O,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,S.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=L,t.whyRejectFile=A,t.acceptFile=async function(e){return null==await A(e)}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function x(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=E(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?x(e):E(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const n=i(94383),r=i(43414),s=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new n.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function x(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await x(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await x(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=x},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},79403:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const S=i(4866),b=i(11944),P=i(59694),M=i(43947),_=i(16475),x=i(77125),E=i(66776),T=i(23175),D=i(44726),k=i(20636),C=i(90957),F=i(39784),O=i(82798),I=i(13779),L=i(24945),A=i(94383),R=i(7162),N=i(12308),B=i(34996),z=i(4691),j=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Z=i(62905),X=i(18295),Y=(0,S.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,r,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,r,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,r,"f",l).push((0,D.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,r,"f",l).toA()}static addLoadingMsg(e){v(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,b.compact)((0,F.toA)(e)).map(O.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Y().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,r,"f",h).entriesByCountDesc()}),(0,E.map)((0,I.leastBy)(e,(e=>[v(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,r,"f",h).incr(e.msg))),Y().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return v(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,x.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=r.summary();if(t.settledCountv(r,r,"f",a).enqueue({name:this.id,l:()=>v(this,n,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>r.onResultChange(),onError:()=>r.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,n,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,b.isEmpty)(e))return{};const[t,i]=(0,I.partition)(e,(e=>"button"===e.type||"POST"===e.method)),n={};return(0,b.isNotEmpty)(i)&&(n.links=(0,b.uniqBy)(i)),(0,b.isNotEmpty)(t)&&(n.buttons=(0,b.uniqBy)(t)),n}t.HealthCheck=Q,r=Q,n=new WeakSet,o=function(){return(0,b.filterInPlace)(v(this,r,"f",s),(e=>!e.isPending)),v(this,r,"f",s)},m=function(e){const t=Y().tap({level:"info",msg:"#summary()",result:(0,X.summarizeHealthChecksSync)({errors:v(this,r,"f",l),skipPending:v(this,r,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,r,!0,"f",u),t.state!==v(this,r,"f",c).last?.state&&v(this,r,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Y().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,T.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,n,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,n,"m",g).call(this,i)}catch(e){return v(this,n,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=r.normalizeMsg(e.msg),n=e.level??((0,O.toS)(i).toLowerCase().includes("error")?"error":(0,O.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,b.compact)([...e?.links??("ok"===n||"pending"===n?this.okLinks:"warn"===n?this.warnLinks:"no-library"===n?this.noLibraryLinks:"error"===n?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:n,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,z.ending)()?a:this.logger.tap({level:Z.HealthCheckLevelToLogLevel[n],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,D.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,n,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new L.BoundedList(10)},u={value:!1},c={value:new L.BoundedList(10)},d={value:new L.BoundedList(100)},h={value:new A.CountingSet},f={value:[]},Q.all=(0,S.lazy)((()=>Object.freeze((0,P.sortBy)(v(r,r,"f",f),(e=>e.sortBy))))),Q.summary=(0,S.lazy)((()=>v(r,r,"m",m).call(r))),Q.resetDebounced=(0,N.debounce)((()=>r.reset()),50)},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const n=i(36535),r=i(77125),s=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,n.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const n=i(11944),r=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,n.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=n(i(70612)),s=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:n}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(n,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const n=i(11944),r=i(88491),s=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:n}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),n))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,n.uniq)((0,n.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,n.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,n.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},65564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),S=i(21084),b=i(98250),P=i(23872),M=i(74836),_=i(4416),x=i(47874),E=i(43414),T=i(96593),D=i(95011),k=i(49312),C=i(36810),F=i(87062),O=i(80870),I=i(14489),L=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,T.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const A=(0,r.lazy)((()=>new S.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:A});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,x.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[n.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const n=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==n){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(n);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:n,whyRejected:e})}const r=i.sha??await n.sha();if(null!=r)if(!0!==await(0,t.isBadSha)(r))try{return await this._build(n,i)}catch(t){e.push(t),A().set(r,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",n);else this.logger.info("skipping: cannot read SHA",n),e.push(new Error("Cannot read "+n.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,L.throwIfInvalidFile_)(e);const i=await e.size(),n=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:n,best:t.uri}),null==i||null==n)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:a,height:o,sha:l,mimetype:u}=t;if(null==r||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:n,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,s.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const n=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(n,r)){const a=(0,D.fitSizes)(e,e.mimetype),o=(0,s.diff)(n,r);if((0,s.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),n=await this.priorIfValid_(t,i);if(null!=n)return n;const r=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,I.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,I.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,D.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),S=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,b=(0,d.pick)(t,"width","height");{let e=o.clone(),t=b;for(const[i,n]of u){const s=Date.now(),a=t,o=this.ap.fileForWidth(n.reducer.name,i.width).wip();e=n.resize(i,e),t=i,n.name===S&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&n.reducer===O.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await n.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+n.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:b,bestFitNameForSq:S}),g=o,p=b):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:S});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),n=p,s=t.outputSize(p??b);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),r.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(n)+" -> "+(0,l.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const n=i(13783),r=i(57743),s=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,n){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(n)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),n=(0,o.toInt)(i[0]),r=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(n)?{file:t,assetId:n,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:n,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,n.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){n.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,n,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",n=t?.[i];if(!(0,o.isEmpty)(n))return n;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},n=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},37251:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=n(i(57441)),s=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;ir?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const n=i(11944),r=i(57743),s=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),n=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,n.push([a,s])))}return n},t.equivalentFitSizes=function(e,t){return(0,n.includesAll)((0,n.compactBlanks)(e).map(l),(0,n.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=n(i(57441)),s=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),S=i(95725),b=i(7162),P=i(48446),M=i(43414),_=i(13378),x=i(27446),E=i(68107),T=i(37251),D=i(34928),k=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,b.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,S.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const O=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const n=(0,D.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:n});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const n=(0,b.mkLogger)("ImageHash("+e+")");if(null==t)return n.throw("Cannot build readable stream");const s=(0,D.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,x.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?T.dctHash:T.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,x.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function L(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:O,impl:I}),t._imageHash_=I,t.isImageHash=L,t.toImageHash=function(e){if(null!=e){if(L(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(L(t))return t}}},t.HashDim=8},36810:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return s(this,n,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,n,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,n,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(n,n,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,n=m,r={value:[]},m.UHD8k=new n("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new n("uhd5k",5120,2880,h.Fit,!1),m.UHD=new n("uhd4k",4096,2160,h.Fit),m.QHD=new n("qhd",3120,1440,h.Fit),m.FHD=new n("fhd",1920,1080,h.Fit),m.HD=new n("hd",1280,720,h.Fit),m.WVGA=new n("wvga",720,480,h.Fit),m.QVGA=new n("qvga",320,240,h.Fit),m.QQVGA=new n("qqvga",160,120,h.Fit),m.S480=new n("s480",480,480,h.Square),m.S240=new n("s240",240,240,h.Square),m.S120=new n("s120",120,120,h.Square),m.S60=new n("s60",60,60,h.Square)},87062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const n=i(4866),r=i(11944),s=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),n=i?.capturedAt;null!=n&&(delete i.capturedAt,(0,s.assignFields)(i,n.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=n(i(57441)),s=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,n)=>t>=(0===n?e[i]:n%i==0?e[n-i]:e[n-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),n=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(n.map(c)),diffHash:(0,s.flatten)(n.map(d))}}},35254:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const n=i(4866),r=i(18941),s=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,n.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=s.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const n=i(4866),r=i(66776),s=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,n.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const n=i(4866),r=i(57743),s=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,n.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,n){const r=(0,d.lteBoth)(e,n)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(n,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(889),s=n(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),S=i(79141),b=i(98250),P=i(95725),M=i(43414),_=i(96593),x=i(27446),E=i(84685),T=i(15465),D=i(68107),k=i(53719),C=i(59387),F=i(34928),O=i(71923),I=i(49312),L=i(49441),A=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),z=(0,a.lazy)((()=>{s.default.simd(M.Settings.enableSIMD.valueOrDefault),s.default.cache(M.Settings.enableVipsCache.valueOrDefault),s.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function j(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,n,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=j,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,A.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const n=B().addParameterContext(e.nativePath);z();const s=await(0,T.readMimeType)(e);if((0,u.blank)(s))return n.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void n.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,x.isVideoMimeType)(s),b=(0,x.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return n.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:b,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),L=(0,h.lt)(C,1),A=(0,x.isSharpMimeType)(s)&&null==t,j=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||L||A||j)n.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:L,isSharpMimeAndNoMinDim:A,isMirrorOrientation:j});else{const i=!1,s=await(0,_.readRawTags)(e,i);if(null==s)n.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof r.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){n.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,s,t,k,C)))}}}(0,x.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,I.isHeifMimeType)(s)&&await(0,O.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,O.heif2img)(e),(e=>({file:e}))))),b&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new S.WrappedError("Failed to extract video frame for "+e,t)}else n.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return n.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...r};n.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){n.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new S.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const n=i(43649),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=r.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*r.secondMs},p1:{x:20*o.MB,y:12*r.secondMs}},p={p0:{x:11*o.MB,y:12*r.secondMs},p1:{x:26*o.MB,y:24*r.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,r=(0,f.commandTimeoutMs)(),s=e.bytes/f.MinIoRate,u=t=>(0,n.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+r+s+c+d),dbMs:i,tagMs:r,copyMs:s,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,n.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,s.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=n(i(57441)),s=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),S=i(23024),b=i(14489),P=i(46517),M=i(15299),_=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),n=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(n)&&_().throw(n,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const x=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return x().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:x,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,b.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,S.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),x=i(6667),E=i(49586),T=i(43414),D=i(68567),k=i(27947),C=i(96593),F=i(27446),O=i(84685),I=i(68107),L=i(53719),A=i(7218),R=i(49441),N=i(12737),B=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function z(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function j(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const n=z("extractMaxBitrate",e),r=T.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,D.extractBitrateKbps)(i)??T.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=j,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await j())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:T.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:T.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=z("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,R.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,I.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,T.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function q(){return T.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=z("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,F.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,T.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const n=z("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void n.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...V(e,d)},s=J(o,r.videoBitrateKbps,i),a=T.Settings.transcodeMaxDim.valueOrDefault,h=(0,x.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(r));0!==o.code&&n.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&z("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),x=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const T=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void x().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return x().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function O(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function I(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...I(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...O(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){x().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return x().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return x().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const n=i(4866),r=i(88491),s=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,n.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const n=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(n,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),S=i(7218),b=i(49441),P=i(36810),M=i(59430),_=i(33185),x=(0,n.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return x().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,b.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],T=["-Z","-"],D=["-o","1"],k=["-t","0","-j"];async function C(e,t){const i=Date.now(),n=await(0,S.dimensions)(e);if(null==n)return x().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(n),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(n)&&(x().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),b=[...E,...T,...D,...v,...k,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*s.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};x().debug("dcraw_emu()",{cmd:w,args:b,opts:F});const O=(0,d.execFile)(w,b,C,F),I=[];function L(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))x().info("dcraw_emu(): warning",{src:e,msg:i});else{x().warn("dcraw_emu(): error",{src:e,msg:i});const n=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});I.push(n)}}O.on("error",L),O.stderr.on("data",L);const A=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},A,(()=>Date.now()-i));if(O.on("close",(()=>R.end())),await t.writeStream_(O.stdout),(0,r.isNotEmpty)(I))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:I,path:e.nativePath});(0,d.endProcess)(O)}t.dcraw_emu_=C},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),x=i(57400),E=i(3955),T=i(43414),D=i(71951),k=i(85352),C=i(81647),F=i(95976),O=i(9483),I=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await x.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(O.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await x.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),x=i(40374),E=i(83837),T=i(43414),D=i(74269),k=i(85352),C=i(81647),F=i(95976),O=i(48924),I=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,O.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,x.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),x=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new x.PlaintextLogFormatter)}));const E=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},25506:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const n=i(59694),r=i(89965);t.kmeans=function(e,t,i){const s=r(e,t,i);return{...s,centroids:(0,n.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const n=i(11944),r=i(75556),s=i(13779),a=i(60346),o=i(6667);function l(e,t,i,n){const r=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,n){const s=new a.Average;return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,n){const s=[];return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,n.range)(r,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,n=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:n/2}),u(e,t,{col:0,row:0},{col:i/2,row:n/2}),u(e,t,{col:0,row:n/2},{col:i/2,row:n}),u(e,t,{col:i/2,row:n/2},{col:i,row:n})];return(0,s.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,n=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:n/2}),c(e,t,{col:0,row:0},{col:i/2,row:n/2}),c(e,t,{col:0,row:n/2},{col:i/2,row:n}),c(e,t,{col:i/2,row:n/2},{col:i,row:n})])},t.greatestHalf=function(e,t){const i=t.col,n=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:n/2}),d(e,t,{col:0,row:0},{col:i/2,row:n}),d(e,t,{col:0,row:n/2},{col:i,row:n}),d(e,t,{col:i/2,row:0},{col:i,row:n})];return(0,s.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const n=[];return l(e,t,i,(e=>n.push(e))),n},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,n.stepRange)(0,t.row,u,(i=>(0,n.stepRange)(0,t.col,o,(n=>(c.clear(),l(t,{col:n,row:i},{col:n+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const n=i(65628),r=i(39938),s=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,n.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,n.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const n=i(39938),r=i(44726),s=i(63774);t.negateFilterName=function(e){if((0,n.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const n=i(4866),r=i(11944),s=i(61570),a=i(7162),o=i(86780),l=(0,n.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],n=[],r=[];for(const a of t)for(const[t,o]of(0,s.entries)(a)){const s=await o(e);!0===s?i.push(t):!1===s?n.push(t):r.push(t)}return{accepted:i,rejected:n,notApplicable:r}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,n]of(0,s.entries)(i))try{if(!1===await n(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:n}){const{accepted:s,rejected:a}=await u.explain(e,...n);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const n=i(61570),r=i(86780);class s{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const n=i(75556),r=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,n.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,n.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),x=i(53719),E="{ready}",T=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,x.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,x.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const n=i(38625),r=i(61570),s=i(84253),a=i(43414),o=(0,s.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,r.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,r.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,n.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(4866),r=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,n.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&T()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},x={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?x:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function T(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=T},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),x=i(94794),E=i(7560),T=i(45005),D=i(20902),k=i(6565),C=i(80534),F=i(86613),O=i(15203),I=i(51053),L=i(33407),A=i(11579),R=i(82590),N=i(55267),B=i(98788),z=i(61659),j=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Z=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>I.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!I.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>I.isMac?"100ms":I.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,O.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:I.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>I.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(I.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:j.NameTagFormats["as-is"],strEnum:j.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),x=i(79015),E=i(98462),T=i(98250),D=i(38846),k=i(23830),C=i(84161),F=i(44911),O=i(43414),I=i(95699),L=i(85560),A=i(98024),R=i(13060),N=i(31086),B=i(16704),z=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,M.libraryDataDirPosixFile)(e)?.join(L.SettingsToml)}async function V(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,A.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function H(e){return(0,m.map)(j(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=j(e);return z().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Z()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await Y()},t.libraryHasSettings=(0,n.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{z().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,x.ee)().on("clearCache",q),(0,x.ee)().on("settingsChanged",q),O.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void z().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ne("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,x.ee)().emitDebounced("settingsChanged")}(r,i),z().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:n}),n){const t=await(0,R.readTomlFile_)(r),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(z().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(z().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function Z(e=(0,A.systemSettingsFile)()){const t=T.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,O.persistedSystemSettings)()),t}function X(e){return Q(j(e))}async function Y(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,O.Settings.libraryDir.value));const i=j(e);return z().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=z().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=z().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,R.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,n.lazy)((()=>P.version)),t.writeSystemSettings_=Z,t.writeAllSettings_=function(e){return K(T.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Y,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,n.lazy)((()=>new Set([O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(O.Settings))te().has(e.key)||e.unset();(0,x.ee)().emit("settingsChanged")}function ne(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),O.Settings.libraryDir.unset(),await Z()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(T.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(T.PosixFile.forMaybe(j())?.unlink("trace")),(0,x.ee)().emit("clearCache"),I.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ne("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ne("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ne("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ne("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ne((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(87748);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),x=i(68074),E=i(54809),T=i(64455),D=i(60299),k=i(3955),C=i(95725),F=i(63410),O=i(9483),I=i(43414),L=i(69301),A=i(82590),R=i(63526),N=i(26352),B=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function j(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=j,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,x.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,x.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);j(this.src)&&(t=Math.max(I.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!j(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,x.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,T.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?I.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,x.datedToLocal)(i.minus(t)),end:(0,x.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:I.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,T.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,x.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function H(e,t){if(I.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(I.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(I.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,T.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,x.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!I.Settings.usePathsToInferDates.valueOrDefault||!I.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:I.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,I.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,I.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",H(e,t)))??(s?void 0:r("path",q(e)))??(I.Settings.useStatToInferDates.valueOrDefault?r("stat",await G(e)):void 0);return B().tap({level:O.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,I.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),x=i(84593),E=i(21084),T=i(98250),D=i(95725),k=i(76531),C=i(7162),F=i(76474),O=i(19658),I=i(2023),L=i(55568),A=i(43414),R=i(13378),N=i(14889),B=i(91464),z=i(53719),j=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Z=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,z.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const n=T.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,ne.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=o?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,o);if(null==h)return void se().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};O.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,x.eqlAsync)(e.sha(),t.sha())||await(0,x.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=T.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=T.PosixFile.for(t),r=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await fe(n)),A.Settings.overwriteOriginal.valueOrDefault||await he(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),ae&&(n.__instance=(0,F.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function x({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>x({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>x({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>x({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>x({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),x=i(43414),E=i(96593);function T(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=T,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function O(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=F(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=O,t.ensureInferredHistoryRecords=async function(e,i,n){const r=T(t.Actions.infer,n),s=(x.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?O(n):void 0)??{};return x.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),I(i,r,s)},t.ensureHistoryRecords=I},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,h.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},28033:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const n=i(889),r=i(25861),s=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function S(e){return null==e||e instanceof n.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(S)):w(e))}function b(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(b).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=S;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(b))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function x(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,x);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,x).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=x,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const n=M(e.Categories);null!=n&&t.push(...n)}for(const n of i){const i=(0,c.pluckDeep)(e,n)?.value;(0,o.blank)(i)||(_(i)?t.push(...x(i)):t.push(...Array.isArray(i)?i:S(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(n.length)),l=s(i.slice(n.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),x=i(98250),E=i(75123),T=i(95725),D=i(9483),k=i(43414),C=i(96879),F=i(69301),O=i(65642),I=i(96593),L=i(17310),A=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function z(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await z(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await z(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),r=(0,T.findFileIndex)(e,n);if(r<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await z(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,n.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,n.last)(e)):(0,n.last)(g(e))}function w(e,t){if((0,n.isEmpty)(e)||(0,n.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,n.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,n.uniqBy)((0,l.toA)(e),(e=>(0,n.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,n.compact)(t).map((e=>y(e))));return(0,n.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(n.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return x(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(x(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=x(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=x;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>T(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function x(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(x(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(x(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(x(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=T,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function O(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function I(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(O)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=O,t.volumeInfoWin=I},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),x=i(62255),E=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,x.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,E.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),x=i(51053),E=i(43414),T=i(39206),D=i(36736),k=i(62255),C=i(49829),F=i(10609),O=i(53719),I=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{E.Settings.libraryDir.watchLater(L),E.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");x.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),x.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",x.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return I().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(I().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(x.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return x.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),E.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,n.lazy)((async()=>{if(!x.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=x){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>x())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const x=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function x(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=x(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=x,t.readUuidFile_=E,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),x=i(14889),E=i(91464),T=i(46852),D=i(37121),k=i(1629),C=i(14195),F=i(42648),O=i(29405),I=i(20902),L=i(17875),A=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),z=i(98250),j=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Z=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([z.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),z.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Z.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Z.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:x.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(n))return;const r=await(0,R.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,E.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Z.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,I.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},95748:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(97742)),s=i(87748),a=i(7127),o=i(12374),l=i(33148),u=i(25516),c=i(38307),d=i(2126),h=i(3142),f=i(29993),m=i(51081),p=i(29663),g=i(43414),y=i(46573),v=i(28437);!async function(){r.default.argv.includes("--help")&&(console.log((0,m.joinLines)(...(0,h.cliWrap)(`This is PhotoStructure's background worker, and is for internal use only.\n${f.DescriptionFooter}`))),r.default.exit(0)),(0,u.setServiceName)(a.ServiceNames.worker),(0,l.setShortProcessNames)(g.Settings.shortProcessNames.valueOrDefault),(0,l.setProcessTitle)(),r.default.argv.includes("--volumes")&&(console.log((0,s.stringify)(await(0,y.volumes)())),r.default.exit(0)),(0,o.addDefaultJsonRevivers)(),(0,d.exitOnStdStream)(),p.onProgressEvt.setShim((async e=>{(0,c.stdoutWrite)(e,void 0)})),(0,v.handleWorkRequests)()}()},48011:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const n=i(75556),r=i(61570),s=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,s.strEnum)(...(0,r.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,n.isNumber)(e.id)}},28437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequests=t.handleWorkRequest=void 0;const r=n(i(97742)),s=i(4866),a=i(7162),o=i(38307),l=i(94329),u=i(39938),c=i(16475),d=i(87748),h=i(2934),f=i(82798),m=i(2126),p=i(24905),g=i(17875),y=i(79141),v=i(48011),w=(0,s.lazy)((()=>(0,a.mkLogger)("worker.Worker")));async function S(e){const t=v.WorkerFunctions[e?.method];if(null==t)throw new Error("invalid method "+(0,d.stringify)(e?.method));return t(e.args[0])}async function b(e){if(e=(0,f.toS)(e),(0,u.blank)(e))return;if(e.trim()===p.ChildServiceExitCommand)return(0,m.exit)({reason:e+" from stdin",status:0});const t=(0,h.parseJSON)(e);if(w().debug("onData",{request:t}),(0,v.isWorkRequest)(t))try{const e=await S(t);(0,o.stdoutWrite)({id:t.id,response:e},!0)}catch(e){const i=(0,c.errorToJson)(e);w().warn("failed to process request",{request:t,error:i}),(0,o.stdoutWrite)({id:t.id,error:i},!1)}else w().warn("not a work request",{request:t,line:e}),(0,o.stdoutWrite)({id:t?.id,request:t,error:"invalid work request"},!0)}t.handleWorkRequest=S,t.handleWorkRequests=function(){!0===r.default.stdin?.readable?(function(){for(const e of["SIGINT","SIGTERM"])r.default.on(e,(e=>(0,m.exit)({reason:e,status:0})))}(),function(){for(const e of["uncaughtException","uncaughtException","disconnect"])r.default.on(e,(e=>{const t=new y.WrappedError("uncaughtException",{cause:e});return(0,g.onError)(t)?(0,m.exit)({error:t,status:(0,c.errorErrno)(t)??1}):void 0}))}(),r.default.stdin.pipe(new l.LineReader).on("data",b),w().info("Child process mode: listening on stdin...")):(0,m.exit)({reason:"process.stdin is not readable",status:13})}},45766:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=n(i(97742)),s=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,s.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},13783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const n=i(88012),r=i(11944),s=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const n=(0,c.toS)(e.v);return(0,s.blank)(n)||"1"===n||(i??(i=new URLSearchParams)).append("v",n),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,n.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,n.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,n.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:s,af:l}){if(null==(0,n.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const S=s&&(0,f.isSafari)((0,h.ua)());S?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const b=r.map((n=>m(y({assetId:e,params:t,reducer:i,width:n}),n)));return null!=l&&b.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(S?"data-":"")+"srcSet"]=b.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,n.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:n="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===n?80:"m"===n?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,n.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of o){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},77125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const n=i(39938),r=i(38625),s=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,n.blank)(e.id)&&!(0,n.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,n.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const n=i(84253);t.ReducerNames=(0,n.strEnum)("fit","sq")},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function x(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=x,t.toPrecisionMaybe=function(e,t){return h(e,(e=>x(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let n=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,n=n.slice(0,r.index)+i(r)+n.slice(r.index+r[0].length);return n}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},61715:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const n=i(84253);t.RunStates=(0,n.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),a=i(21669);async function o(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await o(e,i,r);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,s.tot)(n):a}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=h[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const n=i(11448),r=i(82798);t.ua=(0,n.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const n=i(66776),r=i(75556);function s(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,n.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},99957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),i(95748)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},25861:e=>{e.exports=require("fast-xml-parser")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},89965:e=>{e.exports=require("ml-kmeans")},78932:e=>{e.exports=require("picomatch")},55543:e=>{e.exports=require("plist")},39369:e=>{e.exports=require("process")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=99957);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),a=i(39938),o=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return x(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return x(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function x(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),a=i(88491),o=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),M=i(51053),_=i(43414),x=i(53719);class E extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,x.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+a.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,o.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(M.isWin?3:1)*a.minuteMs,maxTasksPerProcess:_.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,x.commandTimeoutMs)(),minDelayBetweenSpawnMillis:_.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:_.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(11944),o=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),a=i(82798),o=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},84593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(24603),r=i(66776),s=i(61570);var a=i(24603);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(75556),o=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},85563:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(66776),r=i(70208),s=i(6231),a=i(70283),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},12374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const n=i(889),r=i(42748),s=i(43383),a=i(87748),o=i(61570),l=i(44665),u=i(45161),c=i(79141),d=i(65642),h=(0,s.defer)((()=>{r.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:r.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:r.DateTime.name,fromJSON:e=>r.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{h(),(0,a.addJsonRevivers)(n.ExifDateTime,n.ExifDate,n.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,n.BinaryField,c.WrappedError)}))},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(47261),o=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():x()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function x(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=x,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},32370:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(70612),r=i(97742),s=i(4866),a=i(61570),o=i(7162),l=i(55463),u=i(55568),c=i(45113),d=i(42041),h=i(10347),f=i(94845),m=i(51053),p=i(43414);t.logStartup=(0,s.lazy)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,u.serviceName)(),{version:d.version,StartTs:c.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,l.osFullName)(),isPacked:(0,f.isPacked)(),isElectron:m.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:p.Settings.logLevel.valueOrDefault,logServer:p.Settings.logServer.valueOrDefault,httpPort:p.Settings.httpPort.valueOrDefault,libraryDir:p.Settings.libraryDir.valueOrDefault},...(0,h.psenv)()})}))},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),a=i(13779);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},68114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const n=i(97742),r=i(75556),s=i(17078),a=i(6667);function o(){const e=(0,n.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,n.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/s.MB,2)}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),a=i(82798),o=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,o.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(66776),o=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,a.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(m.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function g(e){return(0,o.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,a.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),a=i(1429),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},55463:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(17718),r=i(87561),s=i(70612),a=i(4866),o=i(39938),l=i(88491),u=i(66776),c=i(44726),d=i(82798),h=i(13779),f=i(7162),m=i(28649),p=i(15203),g=i(51053),y=i(49849),v=i(75153),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function x(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=x;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} ร— ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(x())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),M=i(4691),_=i(46852),x=i(46027),E=i(4586),T=i(17875),D=i(98462),k=i(25015),C=i(3955),F=i(51053),O=i(71663),I=(0,o.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,k.isJsonExt)(t)&&(0,C.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))I().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??F.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return I().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,w.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){I().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){I().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!A(n,u)){I().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(I().info("killOldProcs(): killing",{reason:d,json:n}),a.push(N(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,C.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),I().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void I().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,_.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{I().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=B,B.instance=(0,o.lazy)((()=>(0,d.map)((0,E.configDir)(),(e=>new B(D.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return B.instance()?.addPid(e,t)},t.ProcCleaner=(0,o.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,x.setUnrefInterval)((()=>B.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),B.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const n=i(9678),r=i(7162),s=i(55568),a=i(51053);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?n.SimpleShortAppName:n.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(39369).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},18:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.ps=t.isProcEntry=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(75556),d=i(61570),h=i(39784),f=i(82798),m=i(13779),p=i(82128),g=i(7162),y=i(75405),v=i(45113),w=i(3867),S=i(46852),b=i(69317),P=i(9288),M=i(51053),_=i(71663),x=(0,s.lazy)((()=>(0,g.mkLogger)("proc.ps")));function E(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?O:N)).filter((e=>E(e)&&t.includes(e.pid)));return x().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function D(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=E,t.ps=async function(){const e=await(M.isWin?async function(){if(_.PowerShell.instance().ended)return A();const e=await _.PowerShell.instance().executeJsonToA([k,C].join(" "));return null==e?A():D(e)}():async function(){return R(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],I))}());return(0,o.sortBy)(e.filter(E),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const k="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function O(e){if(_.PowerShell.instance().ended)return A(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,S.thenMap)(_.PowerShell.instance().executeJsonToA(t),(e=>D(e)))}const I={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,I),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function R(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function N(e){return R((await(0,b.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...I,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),a=i(34996),o=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>x.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const x=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||x().has(e))return;x().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),a=i(11944),o=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[o.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},25516:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(7127),r=i(4657),s=i(32370),a=i(19658),o=i(55568);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=n.ServiceNames.main);const t=o.serviceName.prior();t!==e&&(a.isTest||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,r.setupLogger)(),(0,s.logStartup)())}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:a=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let o;const l=async i=>{const n=Date.now(),r=await(null!=o?o(i):t(i));return(0,s.ee)().emit("timing",e+(null==o?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(a(e),(async()=>l(e)));return u.setShim=e=>{o=e},u.hasShim=()=>null!=o,u.cache=i,u.cacheDelete=e=>i?.().delete(a(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},97198:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(97742),r=i(58623),s=i(51081),a=i(18991),o=i(43414);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e,...t){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||console.error(e,...t)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),a=i(87748),o=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const x=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=x.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),a=i(6231);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(75556),o=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function x(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=x,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:x(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),a=i(82798),o=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!o.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),a=i(98510),o=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},75288:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const n=i(4866),r=i(66776),s=i(75556),a=i(39784),o=i(85563),l=i(7162),u=i(13378),c=i(65976),d=i(98250),h=i(72461),f=i(6667),m=i(43414),p=i(27947),g=i(96593),y=(0,n.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function S(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function b(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):S(t)}async function P(e){const[i,n,r,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...n,...r,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=S,t.assetFileImageHashFields_=b,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const n=i.capturedAt.toAssetFileFields();return null==n?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...n,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),b(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92356:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(89253),u=i(75556),c=i(61570),d=i(8199),h=i(84253),f=i(49049),m=i(7162),p=i(81666),g=i(3955),y=i(43414),v=i(63526),w=i(3874),S=i(19209),b=(0,n.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function x(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=x;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function T(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function D(e){const t=S.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const n=P.indexOf(t.scheme);if(null==n)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:n,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:x(r),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return b().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=T,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of T(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return b().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return b().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},68668:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const n=i(3874);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,n.uri2nativePath)(e.uri,e.mountpoint))}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},34996:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),M=i(75556),_=i(61570),x=i(26588),E=i(46234),T=i(21669),D=i(7162),k=i(49379),C=i(49273),F="TIMEOUT",O=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e];for((0,M.gt0)(t)&&i.push(new r(F).setTimeout(t));i.some((e=>e.name!==F));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===F)return void O().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,x.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,x.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,r=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(89253),o=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new l.Latch))),this.end=(0,o.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),a=i(43383),o=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},64975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},20681:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,o,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,a,void 0,"f"),h(this,o,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,o,"f")}lastValue(){return d(this,o,"f")?.value??d(this,a,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,o,"f")?.settledMs??d(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,o,"f")?.id;try{const i=await t;if(d(this,o,"f")?.id===n&&h(this,a,i,"f"),d(this,o,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,o,"f");return h(this,o,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,o,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,o,"f")),d(this,o,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,a=!1;const o=()=>s?(a=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&a&&(a=!1,setImmediate(o))}}));return o.isRunning=()=>s,o.prior=()=>r,o.force=async()=>(await r,o()),o}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),a=i(88491),o=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function M(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function x({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const l=a??(o.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,o.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=M,t.rejected=async function(e){return!await M(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=x,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await x({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await x({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await x({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await x({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},70259:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,a,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=(0,m.compact)(d(this,a,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,a){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(a?.(t)),t}let o,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(o=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(a?.(o)):await(i?.()),o}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),a=i(47025),o=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),a=i(43947),o=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,o.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,o.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,a.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const M=["HOME","LANG","USER"],_=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?M:_),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function E(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=E,t.spawnOptions=function(e){const t=e??{};return{...(0,o.omit)(t,"forceCLocale"),env:D({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function D({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,o.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,f.childProcLocale)():{},...E(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,o.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,o.fromEntries)(i)),e.debug("non PS env:",(0,o.fromEntries)(n))}return r}t.childEnv=D},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),M=i(34996),_=i(46027),x=i(49379),E=i(79141),T=i(83837),D=i(95976),k=i(10347),C=(0,a.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function O(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function I(e,i,n,r=0){const a=new Date,o=[];return(0,b.niceable)(i,n)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,_.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&O(e)}),r-250)),o.push((0,_.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,D.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new M.Deferred(m);a.on("error",(e=>v.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(a.stdin);const S=new d.Latch;null==a.stdout?S.resolve():(a.stdout.on("error",(e=>v.push(e))),a.stdout.on("data",(e=>g.push(e))),a.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==a.stderr||r?b.resolve():(a.stderr?.on("error",(e=>v.push(e))),a.stderr?.on("data",(e=>y.push(e))),a.stderr?.on("end",(()=>b.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),C().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const _=y.join("");(0,l.notBlank)(_)&&v.push(new Error(_)),!n&&(0,o.isNotEmpty)(v)&&C().warn(m+" resulted in errors:",v);const D=i.isIgnorableError??x.isIgnorableError,k=v.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:_}}t.endProcess=O,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},24905:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChildServiceExitCommand=void 0,t.ChildServiceExitCommand="--exit"},95298:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),M=i(53525),_=i(17875),x=i(79141),E=i(45512),T=i(7162),D=i(75405),k=i(43414),C=i(69317);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new x.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",a).call(this,e)},a=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(90410)),o=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,o.examples)()))return a.join("$examples",i.posixPathFrom((0,o.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return a.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?a.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},75862:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const n=i(4866),r=i(11944),s=i(21040),a=i(75556),o=i(13779),l=i(7162),u=i(91464),c=i(81108),d=i(26806),h=i(23717),f=i(6451),m=i(64932),p=i(95068),g=i(80654),y=i(88207),v=(0,n.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const n=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:n,closeLabhashes:[n],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function S(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,n.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return S((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=S;const b=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(b,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const n=(0,c.unlabhash)(e),s=S(n);return null!=n&&null!=s&&((0,r.pushUniq)(s.closeLabhashes,e),(0,r.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(n))),s})):void 0}t.bestLabhashName=P},81108:(e,t,i)=>{e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const n=i(4866),r=i(11944),s=i(21040),a=i(66776),o=i(75556),l=i(13779),u=i(70208),c=i(71538),d=i(6451),h=i(80654),f=i(88207),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(x(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],n=[];for(let r=0;re>b?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-n)])}function _(e){const[t,i,n]=v(e),r=(t+16)/116,s=i/500+r,a=r-n/200,o=s*s*s,l=a*a*a,u=o>b?o:(116*s-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>b?l:(116*a-16)/P;return[u*S.X,c*S.Y,d*S.Z]}function x(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=x,t.LabBitZip=(0,n.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const T=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,n]=(0,f.clampRGB)(e),r=Math.max(t,i,n),s=r-Math.min(t,i,n),a=s?r===t?(i-n)/s:r===i?2+(n-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),r?s/r*100:0,r/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,n]=e,r=(200-i)*n/100;return[t,r>0&&r<200?i*n/100/(r<=100?r:200-r)*100:0,r/2]}function O(e){const[t,i,n]=e,r=i*(n<50?n:100-n)/100;return[t,r>0?2*r/(n+r)*100:0,n+r]}function I(e){const t=e[0]/360*6,i=e[1]/100,n=e[2]/100,r=Math.floor(t),s=n*(1-i),a=n*(1-(t-r)*i),o=n*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[n,a,s,s,o,n][l],255*[o,n,n,a,s,s][l],255*[s,s,o,n,n,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(T,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(O(e))},t.hsv2hsl=F,t.hsl2hsv=O,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},26806:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Middle green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep coffee",rgb:"#704241"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},23717:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},6451:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const n=i(75556),r=i(70283);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,n,s]=e,[a,o,l]=t,u=i-a,c=n-o,d=s-l,h=(0,r.sqrt)(n**2+s**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,n.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,n,l]=e,u=(0,r.sqrt)(n**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=n*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let S=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);S+=2*(S<0?1:0)*Math.PI;const b=c-i,P=v-y;let M=y*v==0?0:S-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),x=(i+c)/2,E=(y+v)/2;let T;y*v==0?T=w+S:(T=(w+S)/2,T-=(Math.abs(w-S)>Math.PI?1:0)*Math.PI,T+=2*(T<0?1:0)*Math.PI);const D=(x-50)**2,k=1-.17*Math.cos(T-Math.PI/6)+.24*Math.cos(2*T)+.32*Math.cos(3*T+Math.PI/30)-.2*Math.cos(4*T-63*Math.PI/180),C=1+.015*D/(0,r.sqrt)(20+D),F=1+.045*E,O=1+.015*E*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*T-275)/25)**2),L=2*(0,r.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),A=-1*Math.sin(2*I)*L;return(0,r.sqrt)(Math.pow(b/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*O),2)+A*P/(a*F)*_/(o*O))}t.ciede2000_delta_e=l},65976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const n=i(11944),r=i(75556),s=i(70283),a=i(75862),o=i(81108),l=i(80654),u=i(53682);t.dominantColorsToRgbHex=function(e){return(0,n.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,n.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const n=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=n&&(0,r.gt0)(i)?new c(n,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},17566:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(43947),o=i(87748),l=i(75556),u=i(61570),c=i(13779),d=i(94383),h=i(7162),f=i(7383),m=i(60346),p=i(25506),g=i(6667),y=i(43414),v=i(81108),w=i(6451),S=i(65976),b=i(53682),P=(0,n.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=b.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=b.ModeCount){const i=Date.now(),n=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,n=4*t;g=Math.round(Math.max(i,Math.min(n,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,n).map((e=>{const n=(0,p.kmeans)(f,g,{...x,seed:e}),r=k(n.centroids,f.length);if(r.lengtht&&D(g-1);const s=r.slice(0,t),o=function(e){const t=new m.Average;for(const[i,n]of a.entries()){const r=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=s&&(0,l.times)(n,(()=>t.push(s.value)))}return t.p84}(s);return{...n,centroids:s,description:{kIn:g,kOut:n.centroids.length,kMerged:r.length,score:o,iterations:n.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:n}),T(a,t);const O=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>S.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:O,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,S.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:O,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const n of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,n)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,n))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},x=(0,n.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:n=3}){if(n<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:n,pixelCount:e.length,filteredCount:s.length}),E({labs:e,minK:t,thresh:.75*r,retries:n-1}))}function T(e,t){const i=e.countSum,n=e.size;D(e);const s=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>S.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:n,mergedColors:s,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[n,r]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(n),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:n}):(e.delete(n),e.incr(a.labhash,r))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const n=[];for(const t of e){const e=n.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?n.push(t):e.size+=t.size}const r=t/100;return(0,s.sortBy)(n.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{x.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=T,t.mergeLabhashes=D,t.mergeNearCentroids=k},64932:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},48103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(60346),o=i(43414),l=i(81108),u=(0,n.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,n=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),n.push(e[2])}const r=(i.stdDev??0)+(n.stdDev??0),s=r{Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},80654:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},53682:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},4132:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const n=i(75556),r=i(61570),s=i(84253);t.isModeData=function(e){return(0,n.gt0)(e.mode0)&&(0,n.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},88207:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const n=i(75556),r=i(65113),s=i(44726),a=i(82798),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,n.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,n.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),a=i(88491),o=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(889),r=i(4866),s=i(66776),a=i(75556),o=i(82798),l=i(1058),u=i(76387),c=i(55170),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},76387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(59694),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(44726),f=i(7162),m=i(80294),p=i(44665),g=i(85590),y=i(55170),v=i(45161),w=i(46175),S=i(50140),b=i(82701),P=i(60299),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function x(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function T(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=x(e),n=E(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=x,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):T(e)},t.datedToDateTime=T,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},85590:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(75556),r=i(91464);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},6344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),a=i(77696),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),a=i(88491),o=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},55170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(82798),d=i(2023),h=i(1058),f=i(43414),m=i(45161),p=i(23595),g=i(50140),y=i(54809);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},93125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateIso=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(42748),r=i(39938),s=i(88491),a=i(21040),o=i(66776),l=i(75556),u=i(61570),c=i(98510),d=i(91464),h=i(80294),f=i(44665),m=i(85590),p=i(23595),g=i(64455);function y(e,t,i=n.DateTime.DATETIME_MED){return(0,g.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))}t.recent=function(e,t=5*s.secondMs){return(0,h.isRecentMs)((0,m.datedToMillis)(e),t)},t.fmtDateTime=y;const v=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=f.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(v,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const w=new Map;function S(e="en-US"){return(0,a.getOrSet)(w,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=S,t.fmtDateShort=function(e,t="en-US"){return S(t).format((0,m.datedToMillis)(e))},t.fmtDateIso=function(e,t,i=n.DateTime.DATETIME_MED){return(0,c.opt)(n.DateTime.fromISO(e,{setZone:!0})).filter(g.isValidDate).orElse((()=>(0,o.map)(f.DateInterval.fromISO(e),(e=>e.middle.toDateTime())))).map((e=>y(e,t,i))).getOrElse((()=>e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,d.isString)(e)?e:e.formatted;return((0,u.isObject)(e)&&(0,l.isNumber)(e.timestamp)?(0,g.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,p.parseDateTime)(t)?.toMillis()}},45161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(889),r=i(42748),s=i(47261),a=i(11944),o=i(39938),l=i(88491),u=i(66776),c=i(75556),d=i(61570),h=i(65113),f=i(43414),m=i(44665),p=i(76387),g=i(85590),y=i(55170),v=i(23595),w=i(46175),S=i(50140),b=i(82701),P=i(68074),M=i(54809),_=i(64455),x=i(60299);function E(e,t=2){return null==e?"":(0,h.leftPad)(e,t,"0")}class T{constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(v.ISO_YMD_RE.exec(e)?.groups??v.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||tE(e))).join("-")}toLocal(){return(0,P.datedToLocal)(this)}toDateTime(){return r.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new T(t.year,t.month,t.day)}}function D(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,S.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,(t=>(0,M.zoneToTzOffsetMinutes)((0,g.datedToMillis)(e),t)));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),(n=>(0,u.map)((0,w.getMonth)(e),(r=>(0,u.map)((0,w.getDay)(e),(s=>(0,u.map)((0,w.getHour)(e),(a=>(0,y.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=T,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,c.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${E(s)}:${E(a)}`},t.toExifDateTime=D,t.datedToOffsetMinutes=function(e){return(0,u.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,b.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof m.DateInterval?e.toString({includeOffset:t}):!(0,S.hasTime)(e)||(i??(0,p.datedToPrecisionMs)(e))>=l.dayMs?F(e):D(e,(0,x.getZoneName)(e))?.toISOString({includeOffset:t})};const k="yyyy:MM:dd HH:mm:ss.SSS",C=k+"ZZ";function F(e,t="-"){return(0,a.compact)([(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)]).map((e=>E(e))).join(t)}function O(e){return(0,u.map)(e,(e=>(0,u.map)((0,w.getYear)(e),(t=>new T(t,(0,w.getMonth)(e),(0,w.getDay)(e))))))}function I(e,t){const[i,n]=[e,t].map(g.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof m.DateInterval)return e(t.middle);const i=(0,c.isNumber)(t)?r.DateTime.fromMillis(t):(0,p.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,x.hasZone)(t)?C:k):void 0},t.datedToYMD=F,t.toFuzzyDate=O,t.sameDay=function(e,t){return(0,c.lte)(I(e,t),l.dayMs)},t.diffMillis=I,t.closeTo=function(e,t,i){return(0,u.mapOr)(I(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,g.datedToMillis)(e)||null==(0,g.datedToMillis)(t))return;const[s,a]=[e,t].map((e=>(0,g.datedToMillis)(e))).sort(),o=(a-s)/(n+1),l=(0,x.getZoneName)(e),u=l===(0,x.getZoneName)(t)?l:void 0,c=r.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,S.hasTime)(e)))?O(c):c},t.setZone=function(e,t,i){const n={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,x.hasZone)(e)},r=(0,M.normalizeZone)(t);if(null!=e&&null!=r&&(0,S.hasTime)(e))return e instanceof m.DateInterval?e.setZone(r,n):D(e)?.setZone(r,n)},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,p.datedToDateTime)(e);if(null==i)return;const n=(0,x.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},23595:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(889),l=i(42748),u=i(4866),c=i(11944),d=i(39938),h=i(21040),f=i(75556),m=i(44726),p=i(39784),g=i(13779),y=i(7162),v=i(1058),w=i(81666),S=i(43414),b=i(44665),P=i(76387),M=i(85590),_=i(55170),x=i(45161),E=i(50140),T=i(82701),D=i(92166),k=i(64455),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,T.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function O(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>O(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const t of s){const i=a(t);if(C().debug("parseDated()",{desc:e,s:t,result:i}),null!=i&&(0,k.isValidDate)(i))return i}}t.parseDated=I;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;x.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return x.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},46175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(66776),r=i(75556),s=i(50140);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},50140:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(889),r=i(75556),s=i(61570);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},82701:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(42748);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},68074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(42748),r=i(4866),s=i(88491),a=i(66776),o=i(75556),l=i(43414),u=i(80294),c=i(76387),d=i(85590),h=i(93125),f=i(45161),m=i(46175),p=i(50140),g=i(54809),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(4866),r=i(59694),s=i(75556),a=i(36218),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},54809:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(39938),o=i(66776),l=i(75556),u=i(61570),c=i(65113),d=i(44726),h=i(82798),f=i(13779),m=i(1058);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,x=/(?[-ยฑ+โˆ’])/,E=/[-โˆ’]/,T=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),x,T,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-โˆ’+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const O=/\b(?(?:Etc\/)?GMT)\b/,I=(0,s.lazy)((()=>(0,m.concatRegexp)([O,x,D,m.RegExpOptional.from(k)])));function L(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},64455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.validDay=t.validMonth=t.validYear=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(88491),l=i(43947),u=i(75556),c=i(8199),d=i(7162),h=i(70283),f=i(10408),m=i(79015),p=i(43414),g=i(44665),y=i(76387),v=i(85590),w=i(45161),S=i(68074),b=(0,s.lazy)((()=>(0,d.mkLogger)("date.ValidDate"))),P=(0,s.lazy)((()=>(0,a.compact)(p.Settings.badDates.values.map((e=>(0,y.isoToDated)(e)))))),M=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,w.datedToISO)(e)))))),_=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,S.datedToLocal)(e)))))),x=(0,s.lazy)((()=>(0,a.compact)(P().map((e=>(0,v.datedToMillis)(e))))));function E(e){if(null==e)return!1;const t=D(e);return b().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return E(e)?e:void 0},t.isValidDate=E;const T=String(new Date("bad"));function D(e){try{if(!(0,y.isDated)(e)&&!(0,u.isNumber)(e))return"not Dated";if(String(e)===T)return T;if(e instanceof n.ExifDateTime||e instanceof g.DateInterval||e instanceof r.DateTime||e instanceof w.FuzzyDate){if(!e.isValid)return(0,a.compact)(["not valid",e?.invalidExplanation]).join(": ")}else if(e instanceof Date){if(isNaN(e.getTime()))return"not valid js Date"}else if(e instanceof n.ExifDate){if(!A(e.year,e.month,e.day))return"not valid YMD"}else{const t=r.DateTime.fromObject(e);if(!t.isValid)return"not valid: "+t.invalidExplanation}return x().includes((0,v.datedToMillis)(e))?"bad date (via millis)":_().includes((0,S.datedToLocal)(e))?"bad date (via localtime)":M().includes((0,w.datedToISO)(e))?"bad date (via ISO)":void 0}catch(t){return b().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,f.errorToS)(t)}}t.whyNotValidDate=D,t.mapValidDate=function(e,t){return E(e)?t(e):void 0};const k=(0,s.lazy)((()=>p.Settings.minValidYear.valueOrDefault),o.hourMs),C=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getFullYear()),o.hourMs),F=(0,s.lazy)((()=>new Date(Date.now()+o.dayMs).getMonth()+1),o.hourMs);function O(e){return(0,h.within)(k(),C(),e)}function I(e,t){return(!(0,c.gte)(t,C())||!(0,c.gt)(e,F()))&&(0,h.within)(1,12,e)}function L(e,t,i){return(0,u.gt0)(i)&&r.DateTime.fromObject({year:e,month:t,day:i}).isValid}function A(e,t,i){return O(e)&&(!(0,u.gt0)(t)||I(t,e))&&(!(0,u.gt0)(i)||L(e,t,i))}(0,l.later)((()=>{p.Settings.minValidYear.watchLater((()=>k.unset())),(0,m.ee)().on("clearCache",(()=>{k.unset(),C.unset(),F.unset()}))})),t.validYear=O,t.validMonth=I,t.validDay=L,t.validYMD=A},60299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(889),r=i(75556),s=i(44665),a=i(82701);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(49411)),o=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),M=i(95699),_=i(58676),x=i(51510),E=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function k(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:_.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:_.DefaultDockerLibraryDir},...D()]);const e=(0,o.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,E.homeDir)(),"AppData","Local")]:b.isMac?[a.default.resolve((0,E.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,E.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:k(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(F)}));function F(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),a=i(58676),o=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),a=i(9678),o=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),a=i(63410);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),a=i(11944),o=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,o.getEnv)("USERPROFILE")):e.push((0,o.getEnv)("HOME"));for(const t of(0,a.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),a=i(43414);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),a=i(62936),o=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function x(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await x(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=x},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(29405),o=i(51053),l=i(71663),u=i(10156);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),a=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,a.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,a.env)()[e]="true":delete(0,a.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),a=i(39938),o=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,o.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),a=i(39938),o=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),a=i(82798),o=i(91464);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),a=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),a=i(82798),o=i(1058),l=i(10408),u=i(53525);function c(e){return(0,a.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,o.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},90756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const n=i(53525);class r extends Error{constructor(e){super(e+n.InternalErrorFlag)}}t.InternalError=r},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),a=i(19658),o=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||a.isTest||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(16475),o=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(11944),o=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,o.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,a.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function a(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=a,t.ee=(0,r.lazy)(a)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),a=i(9483),o=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,o.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:a.LogLevels.warn,updateReadyToInstall:a.LogLevels.warn,clearCache:a.LogLevels.trace,clearDbCache:a.LogLevels.trace,clearToolCache:a.LogLevels.trace,error:a.LogLevels.error,fatal:a.LogLevels.fatal,fileChanged:a.LogLevels.trace,invalidFile:a.LogLevels.warn,mountpointsChanged:a.LogLevels.info,nonFatal:a.LogLevels.warn,pause:a.LogLevels.info,progress:a.LogLevels.info,updateProgress:a.LogLevels.info,reloadLicenses:a.LogLevels.info,resume:a.LogLevels.info,settingsChanged:a.LogLevels.info,showAbout:a.LogLevels.info,syncing:a.LogLevels.info,taskResult:a.LogLevels.info,timing:a.LogLevels.trace,vacuuming:a.LogLevels.info,volumesChanged:a.LogLevels.info}),t.TaskNameToLevel={checkOperations:a.LogLevels.info,repairAsset:a.LogLevels.info,repairAssetFile:a.LogLevels.info,runTagMaintenance:a.LogLevels.info,syncDir:a.LogLevels.info}},87489:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),M=i(59694),_=i(38625),x=i(88491),E=i(43383),T=i(24603),D=i(16475),k=i(1429),C=i(87748),F=i(21040),O=i(66776),I=i(75556),L=i(61570),A=i(20636),R=i(39784),N=i(7162),B=i(70283),z=i(55568),j=i(14889),V=i(45113),W=i(3917),U=i(31329),H=i(37086),q=i(34996),G=i(36079),$=i(91641),J=i(95557),K=i(17354),Z=i(21142),X=i(80294),Y=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),ae=i(4931),oe=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,N.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,H.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,X.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,I.gt)(i,V.StartTs):n}function Se(e){const t=(0,M.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,C.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,I.isNumber)(e.pid)&&(0,_.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=x.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends J.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),$.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),a.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),o.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,o,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,z.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),$.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,B.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,R.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,oe.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,oe.toNativePath_)(t),x.hourMs)){const e=await(0,ae.readFileMaybe)((0,oe.toNativePath_)(t)),n=(0,C.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,k.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const a=(0,k.flatten)(i.map((e=>e.tasks))),o=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,M.sortUniqBy)(a.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,I.gt)((0,H.tsFromUid)(e?.uid),o))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,F.deleteIf)(p(this,o,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,z.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,a,"f").values()],tasks:[...p(this,o,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,H.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,C.stringify)((0,L.pick)(t,"name","args"));return p(this,a,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,H.uid)(),name:e,args:t},r=new q.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,z.processName)()+"-error",error:"uncaught rejection: "+(0,Y.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,o,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,R.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*x.secondMs);await(0,Z.untilTrue)((()=>{this.vacuum();const t=0===p(this,o,"f").size;return t||e(),t}),{timeoutMs:j.ShortCommandTimeoutMs,intervalMs:x.secondMs}),p(this,o,"f").destroy(),(0,O.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,z.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,o,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let a;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:a,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-"+e.name,error:(0,Y.errorToS)(i)}}return null==a&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),a={uid:t.uid,ts:Date.now(),pid:(0,z.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,o,"f").get(t.uid)?.resolve(a),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:a}),await this.broadcastEvent_({name:"taskResult",args:[a]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:a}),a},l={value:(0,E.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,z.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,D.shortStack)());p(r,r,"f",l).call(r);const e=(0,O.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,o,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,O.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),a=i(91464),o=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),M=i(11944),_=i(92585),x=i(39938),E=i(88491),T=i(24603),D=i(1429),k=i(87748),C=i(66776),F=i(75556),O=i(61570),I=i(98510),L=i(65113),A=i(44726),R=i(39784),N=i(82798),B=i(13779),z=i(34996),j=i(46852),V=i(7383),W=i(21142),U=i(83486),H=i(49379),q=i(79015),G=i(79378),$=i(7162),J=i(6667),K=i(51053),Z=i(91464),X=i(2073),Y=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),ae=i(59873),oe=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,j.thenMap)(this.directoryEntry(),(e=>e.children()))))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,x.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,j.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,j.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,C.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,j.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,R.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Y.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(x.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,V.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,V.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,j.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,j.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,j.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,j.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,j.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,j.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,j.thenMap)(this.statTimes(),J.min)}minStatDate(){return(0,j.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,j.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,j.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,j.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,j.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,j.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,j.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,j.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,j.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,j.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,j.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,j.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,O.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new oe.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,V.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new z.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,j.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,F.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new z.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*E.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},56640:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(43414),r=i(17310),s=i(63526),a=i(3955);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),a=i(82798),o=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),a=i(7162),o=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,a.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),a=i(91641),o=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends o.EndableWrapper{static async for(e,t,i=a.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const o=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=o.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(o.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,o,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44470)),l=a(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),a=i(3955),o=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},64067:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(78932)),u=i(4866),c=i(11944),d=i(59694),h=i(39938),f=i(66776),m=i(44726),p=i(82798),g=i(13779),y=i(36218),v=i(51498),w=i(7162),S=i(2023),b=i(46852),P=i(4586),M=i(10156),_=i(85943),x=i(82341),E=i(20902),T=i(9483),D=i(51053),k=i(38336),C=i(51776),F=i(43414),O=i(77390),I=i(98462),L=i(64546),A=i(28659),R=i(1391),N=i(69716),B=i(95725),z=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),j=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=j.get(t);if(null!=i)return i;const n=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),r=V.test(t)||n.isDirectorySync(),s=(0,R.native2posix)(n.nativePath),a=r?(0,m.ensureSuffix)(s,"/"):s;return j.set(t,a),j.set(a,a),j.set(n.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(n.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),z().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,z().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,S.pairToObject)(this.reason,a(this,n,"m",r).bind(this)):{}}}n=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return z().tap({msg:"apply()",level:i?T.LogLevels.debug:T.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){z().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):z().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows application support"},{s:"Application Support",desc:"Windows application support"},{s:"Applications",desc:"macOS Applications directory"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files?( x86)",desc:"Windows program"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"temp",desc:"temporary file"},{s:"Temporary Items",desc:"temporary file"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary file"},{s:"Trash",desc:"trash directory"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,n){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new U(`**/${t}/${r[0]}/`,n)),r.length>1&&e.push(new U(`**/${t}/(${r.join("|")})/`,n))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System?(32)","SysWOW64","Temp"],"Windows system directory"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const n=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];return t("var",n,"Linux /var"),t("mnt",n,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Accessibility*","AccessibilityBundles","Accounts","Address Book Plug-Ins","Apple","AppleMediaServices","Application Support","AssetCache","Assets","AssetsV2","AssetTypeDescriptors","Assistant","Audio","AWD","BridgeSupport","Bundles","CacheDelete","Caches","CardKit","Classroom","ColorPickers","Colors","ColorSync","Components","Compositions","ConfigurationProfiles","Contextual Menu Items","CoreAccessories","CoreAnalytics","CoreImage","CoreMediaIO","CoreServices","CryptoTokenKit","DefaultsConfigurations","Desktop Pictures","Developer","Dictionaries","DifferentialPrivacy","DirectoryServices","Display","Displays","DistributedEvaluation","Documentation","DriverExtensions","DTDs","DuetActivityScheduler","Extensions","FDR","FeatureFlags","Filesystems","Filters","Fonts","Frameworks","GPUBundles","Graphics","HIDPlugins","IdentityServices","Image Capture","Input Methods","InstallerSandboxes","InternetAccounts","Internet Plug-Ins","Isp","iTunes","Java","KerberosPlugins","KernelCollections","Kernels","Keyboard Layouts","Keychain","Keychains","LASecureIO","LaunchAgents","LaunchDaemons","Lexicons","LinguisticData","LocationBundles","LoginPlugins","Logs","MediaStreamPlugins","Messages","MessageTracer","Modem Scripts","MonitorPanels","MultiversePlugins","NetworkServiceProxy","OnBoardingBundles","OpenDirectory","OpenSSL","OSAnalytics","PairedSyncServices","Password Server Filters","PDF Services","Perl","PreferenceBundles","PreferencePanes","Preferences","PreferencesSyncBundles","Printers","PrivateFrameworks","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Recents","Ruby","RunningBoard","Sandbox","ScreenReader","Screen Savers","Script Editor Plugins","ScriptingAdditions","Scripts","Security","Services","Sounds","Speech","SpeechBase","Spotlight","StagedDriverExtensions","StagedExtensions","StartupItems","SyncServices","SystemConfiguration","SystemExtensions","SystemMigration","SystemProfiler","Tcl","Templates","TextEncodings","TextInput","Trial","Updates","UserEventPlugins","UserNotifications","User Pictures","User Template","Video","VideoProcessors","WebServer","Widgets","xpc"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code"),t("appdata",["local","locallow","roaming"],"Windows default AppData"),t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:ne,notInHiddenPhotoStructureDir:ae,notNoMedia:re,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ae}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&z().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):z().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const n=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,s]=(0,g.partition)(n,(e=>e.pattern.endsWith("/")));return{dir:r,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Y=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().dir}async function ie(e){return k.Predicates.whyRejected(e,...te(e))}function ne(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,b.thenNot)((0,A.hasNoMedia)(e))}function se(e){return(0,b.thenNot)((0,L.isHidden)(e))}function ae(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,x.libraryDirPosixFile)(),(0,x.libraryOriginalsDirPosixFile)(),F.Settings.argvScanPaths.values,F.Settings.scanPaths.values]));return z().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,O.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ae},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(11944),o=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),a=i(21040),o=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,a.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},18941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(53221),r=i(4866),s=i(39938),a=i(7162),o=i(79141),l=i(25015),u=i(96593),c=i(63526),d=i(27446),h=i(98250),f=i(53755),m=i(76531),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},19653:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),M=b(i(44470)),_=i(92332),x=i(11944),E=i(37609),T=i(88491),D=i(24603),k=i(19067),C=i(66776),F=i(75556),O=i(23175),I=i(20636),L=i(82798),A=i(19658),R=i(1058),N=i(55568),B=i(91641),z=i(95557),j=i(4691),V=i(17354),W=i(53525),U=i(9483),H=i(6231),q=i(53719),G=i(95694),$=i(95725),J=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,x.compactBlanks)([H.TokenRadix.encode(w(this,r,"f",s)),N.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??B.EndableRanks.postdb,(0,q.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,V.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,O.randomFloat)(2,4)),w(r,r,"f",o).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,E.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,x.filterInPlace)(w(r,r,"f",o),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(w(this,d,"f"),(e=>(0,_.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,j.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,I.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),a=i(95725);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},86472:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),M=i(28807),_=i(91641),x=i(17354),E=i(79015),T=i(3955),D=i(8177),k=i(43414),C=i(91464),F=i(37086),O=i(59873),I=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class R extends M.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,D.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,D.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}R.instance=new R;class N extends M.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,I.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:_.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,F.uid)(),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",o).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,a,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault),this.check=(0,x.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>R.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),a=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",o).call(this):!a&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,E.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,I.toNativePath_)(e.target);const i=e.watchDebounceMs??k.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>R.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),R.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,a,void 0,"f")}}t.FsWatcher=N,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),k.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:k.Settings.statTimeoutMs.valueOrDefault}),u(this,a,void 0,"f"),!1;const t=(0,C.sortIgnoreCase)(e);return!(0,v.eql)(c(this,a,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,a,"f")}),u(this,a,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,O.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),a=i(44726),o=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},40374:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44470)),s=n(i(87561)),a=i(76402),o=n(i(65628)),l=i(21040),u=i(1058);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),a=i(76402),o=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),a=i(75556),o=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),a=i(51053),o=i(10609),l=/^\/dev(?:\/|$)/i,u=a.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||s.isTest?/^\/private\//i:void 0,d=a.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),a=i(47987);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const a=s(i(49411)),o=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,o.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const M=(0,o.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function _(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&M().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return E(e,i,t);const n=await Promise.race([x(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function x(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(a.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function E(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,a.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&E(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,_)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=_},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function M(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return k(e).some(M)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return x((0,y.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const _=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=_.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function E(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function k(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return e.startsWith("\\\\")}function F(e){return(0,d.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=E,t.grandParentBasename=function(e){return E(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return D(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(w.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&k(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=k(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),F([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),F([...r,...s])},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=C,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(C(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),a=i(11944),o=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function x(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...x(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),M=i(19067),_=i(66776),x=i(75556),E=i(61570),T=i(20636),D=i(49049),k=i(17078),C=i(82798),F=i(13779),O=i(7162),I=i(14889),L=i(91464),A=i(46852),R=i(7383),N=i(21142),B=i(69317),z=i(14195),j=i(53525),V=i(49379),W=i(9483),U=i(6231),H=i(51053),q=i(49586),G=i(71663),$=i(43414),J=i(78362),K=i(3874),Z=i(19209),X=i(25116),Y=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),ae=i(35694),oe=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,O.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,z.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,z.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,ae.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,oe.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,oe.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,x.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,x.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,x.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},23872:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(82798),o=i(13779),l=i(46852),u=i(38336),c=i(43414),d=i(27947),h=i(96593),f=i(28033),m=i(27446),p=i(15465),g=i(68107),y=i(61473),v=i(98462),w=i(56640),S=i(64067),b=i(76531);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):void 0}async function _(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):void 0)}async function x(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):void 0)}async function E(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function T(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){if(0!==c.Settings.keywordBlocklist.values.length)return(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?void 0:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):void 0}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,b.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function O(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,S.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:O}]}function L(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:x},{notRejectedRating:T},{notExcludedKeyword:D}]}async function A(e,t){return await u.Predicates.whyRejected(e,...t??L(e))??await(0,S.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,n.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=O,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,S.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=L,t.whyRejectFile=A,t.acceptFile=async function(e){return null==await A(e)}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),a=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),a=i(4866),o=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,a.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,o.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),a=i(7162),o=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(87561));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),a=i(4866),o=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const M=(0,a.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function _(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function x(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=E(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=_,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():_(e)))})),t.slowDirs=(0,a.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){_(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?x(e):E(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=E},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),a=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,a.upcaseDriveLetters)(e[0]),...e.slice(1))}},69716:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const n=i(94383),r=i(43414),s=i(3955);t.seemsLikeSymlinkLoop=function(e){const t=new n.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),a=i(39938),o=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,o.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function M(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=M,t.statEql=function(e,t){return null==M(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),a=i(39938),o=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,a.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),a=i(66776),o=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,o.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,o.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,a.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},22143:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(70612)),s=i(4866),a=i(66776),o=i(44726),l=i(64975),u=i(53525),c=i(51053),d=i(98462),h=i(9288),f=i(27175);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),a=i(39938),o=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},74836:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkNativePath_=t.trashOrUnlinkFileUri_=t.trashOrUnlinkFileUris_=t.unlink=void 0;const o=s(i(93977)),l=a(i(41313)),u=i(4866),c=i(11944),d=i(39938),h=i(39784),f=i(7162),m=i(14889),p=i(46852),g=i(21142),y=i(79015),v=i(43414),w=i(3874),S=i(53719),b=i(95725),P=i(76531),M=(0,u.lazy)((()=>(0,f.mkLogger)("fs.Unlink")));async function _(e,t="warn"){for(const i of(0,h.toA)(e))try{null!=i&&await o.unlink((0,b.toNativePath_)(i))}catch(e){M().log(t,"Failed to unlink "+i,{error:e})}}async function x(e){if(!await(0,P.nativePathIsFile)(e))return M().tap({level:"warn",msg:"trashOrUnlinkFileUri_: path is not a file, refusing to unlink.",result:{nativePath:e,unlinked:!1}});if(v.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,l.default)(e,{glob:!1}),await(0,g.untilTrue)((()=>(0,p.thenNot)((0,P.nativePathIsFile)(e))),{timeoutMs:m.ShortCommandTimeoutMs}))return M().info("soft-delete("+e+") successful"),{nativePath:e,unlinked:!0};M().warn("soft-delete("+e+") didn't seem to work: the file is still there?")}catch(e){M().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}return await _(e),(0,y.ee)().emit("fileChanged",e),M().info("unlink("+e+") successful"),{nativePath:e,unlinked:!0}}t.unlink=_,t.trashOrUnlinkFileUris_=async function(e){return(0,p.mapAsyncSerial)({name:"trashOrUnlinkFileUris_",arr:(0,c.uniqBy)(e,(e=>e.uri)),f:async({uri:e,mountpoint:t})=>{const i=await(0,w.uri2nativePath)(e,t);if((0,d.blank)(i))return M().tap({msg:"trashOrUnlink: Failed to resolve URI to delete",result:void 0,meta:{uri:e,mountpoint:t}});try{return M().tap({msg:"trashOrUnlink",result:await x(i),meta:{nativePath:i,uri:e,mountpoint:t}})}catch(n){M().error("Failed to unlink()",{nativePath:i,uri:e,mountpoint:t,error:n})}},timeoutMs:(0,S.commandTimeoutMs)()})},t.trashOrUnlinkFileUri_=async function(e,t){const i=await(0,w.uri2nativePath)(e,t);return(0,d.blank)(i)?M().tap({msg:"trashOrUnlinkFileUri_: null nativePath",result:{nativePath:i,unlinked:!1},meta:{uri:e,mountpoint:t}}):M().tap({msg:"trashOrUnlinkFileUri_()",result:await x(i),meta:{uri:e,mountpoint:t}})},t.trashOrUnlinkNativePath_=x},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),a=i(44726),o=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),a=i(76402),o=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},85825:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},79403:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},w=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const S=i(4866),b=i(11944),P=i(59694),M=i(43947),_=i(16475),x=i(77125),E=i(66776),T=i(23175),D=i(44726),k=i(20636),C=i(90957),F=i(39784),O=i(82798),I=i(13779),L=i(24945),A=i(94383),R=i(7162),N=i(12308),B=i(34996),z=i(4691),j=i(20681),V=i(70259),W=i(42648),U=i(10408),H=i(49379),q=i(43414),G=i(53719),$=i(75153),J=i(85825),K=i(6565),Z=i(62905),X=i(18295),Y=(0,S.lazy)((()=>(0,R.mkLogger)("health.HealthCheck")));class Q{static traceLater_(e,t){const i=new B.Deferred(e);i.catch((t=>{v(this,r,"f",l).push(e+": failed: "+(0,U.errorToS)(t)),this.onResultChange()})),v(this,r,"m",o).call(this).push(i);try{return i.observe((0,C.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return v(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){v(this,r,"f",l).push((0,D.isString)(e)?e:(0,U.errorToS)(e)),this.onResultChange()}static lastErrors(){return v(this,r,"f",l).toA()}static addLoadingMsg(e){v(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,b.compact)((0,F.toA)(e)).map(O.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return Y().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:v(this,r,"f",h).entriesByCountDesc()}),(0,E.map)((0,I.leastBy)(e,(e=>[v(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=v(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,E.map)(e,(e=>v(this,r,"f",h).incr(e.msg))),Y().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?K.HealthCheckIds.values:[];return q.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return v(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,x.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=v(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){const e=this.allCritical().length;let t=r.summary();if(t.settledCountv(r,r,"f",a).enqueue({name:this.id,l:()=>v(this,n,"m",p).call(this,o)}),ttlMs:g});for(const e of this.settings)q.Settings[e].watchLater((()=>this.reset()));this.result.watchLater({onChange:()=>r.onResultChange(),onError:()=>r.onResultChange()})}isStale(){return this.result.isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return this.result.settledCount()}reset(){this.result.unset(),this.onReset?.()}setTTL(e){this.result.setTTL(e)}refresh(){return this.result.refresh()}isSkipped(){return q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return this.result.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.result.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){return await(0,k.thenOrTimeoutAs)({f:this.result(),timeoutMs:e,as:void 0})??v(this,n,"m",y).call(this,"Timeout","warn")}}function ee(e){if((0,b.isEmpty)(e))return{};const[t,i]=(0,I.partition)(e,(e=>"button"===e.type||"POST"===e.method)),n={};return(0,b.isNotEmpty)(i)&&(n.links=(0,b.uniqBy)(i)),(0,b.isNotEmpty)(t)&&(n.buttons=(0,b.uniqBy)(t)),n}t.HealthCheck=Q,r=Q,n=new WeakSet,o=function(){return(0,b.filterInPlace)(v(this,r,"f",s),(e=>!e.isPending)),v(this,r,"f",s)},m=function(e){const t=Y().tap({level:"info",msg:"#summary()",result:(0,X.summarizeHealthChecksSync)({errors:v(this,r,"f",l),skipPending:v(this,r,"f",u),healthCheckResults:e??this.allCritical().map((e=>e.toResultSync()))})});return t.settled&&w(this,r,!0,"f",u),t.state!==v(this,r,"f",c).last?.state&&v(this,r,"f",c).push({state:t.state,ts:Date.now()}),t},p=async function(e){Y().debug("#wrapLater() starting",{id:this.id});try{const t=this.timeoutMs??(0,G.commandTimeoutMs)();if((0,W.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,T.randomInt)(.3*t,.7*t)),this.isSkipped())return v(this,n,"m",g).call(this,{level:"disabled",msg:["Disabled by "+q.Settings.skipHealthCheckIds.key]});const i=await(0,k.thenOrTimeoutError)(e(),t);return v(this,n,"m",g).call(this,i)}catch(e){return v(this,n,"m",y).call(this,e)}},g=function(e,t="#toResult"){const i=r.normalizeMsg(e.msg),n=e.level??((0,O.toS)(i).toLowerCase().includes("error")?"error":(0,O.toS)(i).toLowerCase().includes("warn")?"warn":"ok"),s=(0,b.compact)([...e?.links??("ok"===n||"pending"===n?this.okLinks:"warn"===n?this.warnLinks:"no-library"===n?this.noLibraryLinks:"error"===n?this.errorLinks:[])??[],...this.links??[]]),a={section:this.section,id:this.id,ts:Date.now(),level:n,elapsedMs:this.result.elapsedMs(),msg:i,...ee(s)};return(0,z.ending)()?a:this.logger.tap({level:Z.HealthCheckLevelToLogLevel[n],msg:t,result:a})},y=function(e,t){this.logger.warn("#toErrorResult",{error:e,level:t});const i=(0,D.stripSuffix)(this.pendingMsg,"โ€ฆ")+" failed:\n"+((0,E.map)(e,U.errorToS)??"Unknown error");return t??(t=!this.isCritical||!(0,H.isFatalError)(e)&&i.toLowerCase().includes("warn")?"warn":"error"),v(this,n,"m",g).call(this,{msg:i,level:t},"#toErrorResult")},s={value:[]},a={value:new V.Promises("HealthCheck",(()=>(0,$.cpuCount)()))},l={value:new L.BoundedList(10)},u={value:!1},c={value:new L.BoundedList(10)},d={value:new L.BoundedList(100)},h={value:new A.CountingSet},f={value:[]},Q.all=(0,S.lazy)((()=>Object.freeze((0,P.sortBy)(v(r,r,"f",f),(e=>e.sortBy))))),Q.summary=(0,S.lazy)((()=>v(r,r,"m",m).call(r))),Q.resetDebounced=(0,N.debounce)((()=>r.reset()),50)},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},62905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const n=i(36535),r=i(77125),s=i(23022),a=i(55568),o=i(82341),l=i(15203),u=i(43414),c=i(91499);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,n.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},91499:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const n=i(11944),r=i(82041);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,n.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},32940:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=n(i(70612)),s=i(4866),a=i(36535),o=i(88491),l=i(43383),u=i(75556),c=i(17078),d=i(68114),h=i(55568),f=i(43414),m=i(79403);function p({desc:e,bytes:t,level:i,thresholdBytes:n}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(n,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usageโ€ฆ",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},18295:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const n=i(11944),r=i(88491),s=i(43383),a=i(43947),o=i(1429),l=i(77125),u=i(61715),c=i(4866),d=i(7162),h=i(55568),f=i(34996),m=i(43414),p=i(62905),g=i(91499),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:n}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),n))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=e.healthCheckResults,i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,n.uniq)((0,n.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",...h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,n.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,n.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},65564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.isBadSha=t.mkPreviewAssetFile_=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(88491),l=i(57743),u=i(87748),c=i(66776),d=i(61570),h=i(13779),f=i(7162),m=i(13378),p=i(92356),g=i(68668),y=i(90756),v=i(79141),w=i(98462),S=i(21084),b=i(98250),P=i(23872),M=i(74836),_=i(4416),x=i(47874),E=i(43414),T=i(96593),D=i(95011),k=i(49312),C=i(36810),F=i(87062),O=i(80870),I=i(14489),L=i(31216);t.mkPreviewAssetFile_=async function(e){const t=await(0,T.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};const A=(0,r.lazy)((()=>new S.FileCache({name:"img.badShaCache",maxSize:256,timeoutMs:o.minuteMs}))),R=Promise.resolve(!1);t.isBadSha=(0,m.shim1)({name:"isBadSha",impl:e=>R,cache:A});class N{constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,f.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,x.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[n.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,d.pick)(e,"id","uri"))));const e=[];for(const i of this.assetFiles){const n=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(i));if(null==n){this.logger.info("skipping: failed to get PosixFile",{af:i}),e.push(new Error("Cannot get path from URI "+(0,u.stringify)((0,d.pick)(i,"uri","mountpoint","nativePath"))));continue}{const e=await(0,P.whyRejectFile)(n);(0,a.blank)(e)||this.logger.info("skipping: rejected",{pf:n,whyRejected:e})}const r=i.sha??await n.sha();if(null!=r)if(!0!==await(0,t.isBadSha)(r))try{return await this._build(n,i)}catch(t){e.push(t),A().set(r,!0),this.logger.warn("Failed to set shown file to ",{best:i,error:t})}finally{this.ap.parent.clear()}else this.logger.info("skipping: bad SHA",n);else this.logger.info("skipping: cannot read SHA",n),e.push(new Error("Cannot read "+n.nativePath))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,L.throwIfInvalidFile_)(e);const i=await e.size(),n=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:n,best:t.uri}),null==i||null==n)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:a,height:o,sha:l,mimetype:u}=t;if(null==r||null==a||null==o||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:n,filesize:i,width:a,height:o,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,s.compact)(C.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,u.stringify)({priorInfo:i,info:t}));const n=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(n,r)){const a=(0,D.fitSizes)(e,e.mimetype),o=(0,s.diff)(n,r);if((0,s.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async _build(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),n=await this.priorIfValid_(t,i);if(null!=n)return n;const r=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},C.ImageSize.sq().length+C.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,I.sharpReadable_)({src:e,minDim:C.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,I.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"ยฐ")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const u=(0,D.fitSizes)(t,t.mimetype),f=[],m=[];let p,g;const y=C.ImageSize.largestSq(),S=(0,h.leastBy)(u,(([e,t])=>(0,c.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,b=(0,d.pick)(t,"width","height");{let e=o.clone(),t=b;for(const[i,n]of u){const s=Date.now(),a=t,o=this.ap.fileForWidth(n.reducer.name,i.width).wip();e=n.resize(i,e),t=i,n.name===S&&(g=e.clone(),p=i),(0,l.dmegapixels)(i)>=1&&n.reducer===O.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await n.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+n.name+") "+(0,l.fmtDim)(a)+" -> "+(0,l.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),f.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:b,bestFitNameForSq:S}),g=o,p=b):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:S});let e=!1;for(const t of C.ImageSize.sq()){const i=Date.now(),n=p,s=t.outputSize(p??b);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),r.onProgress(),f.push(a),this.logger.debug("resize("+t.name+") "+(0,l.fmtDim)(n)+" -> "+(0,l.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of f){const i=await e.unwip_();t.delete(i.nativePath)}await(0,M.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,M.unlink)(f),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=N},31053:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const n=i(13783),r=i(57743),s=i(9381),a=i(66776),o=i(75556),l=i(46852),u=i(3955),c=i(7162),d=i(70283),h=i(91464),f=i(7218),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,n){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(n)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),n=(0,o.toInt)(i[0]),r=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(n)?{file:t,assetId:n,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:n,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,n.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},8104:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(4866),o=i(11944),l=i(13783),u=i(9381),c=i(61570),d=i(65113),h=i(88012),f=i(13779),m=i(7162),p=i(91464),g=i(46852),y=i(53525),v=i(6667),w=i(31053);t.AssetPreviews=class{constructor(e,t){n.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,n,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",n=t?.[i];if(!(0,o.isEmpty)(n))return n;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},n=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},37251:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=n(i(57441)),s=i(1429),a=i(81108),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;ir?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},34928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(33714),o=i(82798),l=i(36143);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[xร—]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},7218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(4866),r=i(75556),s=i(7162),a=i(46852),o=i(68107),l=i(23024),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},95011:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const n=i(11944),r=i(57743),s=i(27446),a=i(36810),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),n=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,n.push([a,s])))}return n},t.equivalentFitSizes=function(e,t){return(0,n.includesAll)((0,n.compactBlanks)(e).map(l),(0,n.compactBlanks)(t).map(l))}},71923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(39938),r=i(43947),s=i(82798),a=i(4866),o=i(7162),l=i(55463),u=i(14889),c=i(69317),d=i(79015),h=i(95487),f=i(79621),m=i(51053),p=i(43414),g=i(50886),y=i(16114),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},50886:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(43947),o=i(17078),l=i(7162),u=i(69317),c=i(79015),d=i(9288),h=i(43414),f=i(7218),m=i(49441),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:s.minuteMs,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},49312:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(39938),r=i(82798),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),a=i(39784),o=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},72461:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=n(i(57441)),s=i(4866),a=i(11944),o=i(39938),l=i(88491),u=i(57743),c=i(7383),d=i(81108),h=i(65976),f=i(17566),m=i(48103),p=i(4132),g=i(20902),y=i(53525),v=i(21084),w=i(98250),S=i(95725),b=i(7162),P=i(48446),M=i(43414),_=i(13378),x=i(27446),E=i(68107),T=i(37251),D=i(34928),k=i(58061),C=i(14489);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,b.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,S.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const O=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const n=(0,D.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:n});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const n=(0,b.mkLogger)("ImageHash("+e+")");if(null==t)return n.throw("Cannot build readable stream");const s=(0,D.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,x.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?T.dctHash:T.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,x.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function L(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:O,impl:I}),t._imageHash_=I,t.isImageHash=L,t.toImageHash=function(e){if(null!=e){if(L(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(L(t))return t}}},t.HashDim=8},36810:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(47261),o=i(4866),l=i(57743),u=i(17078),c=i(13779),d=i(43414),h=i(80870),f=i(23024);class m{static sq(){return s(this,n,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,n,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,n,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(n,n,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"ร—"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,n=m,r={value:[]},m.UHD8k=new n("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new n("uhd5k",5120,2880,h.Fit,!1),m.UHD=new n("uhd4k",4096,2160,h.Fit),m.QHD=new n("qhd",3120,1440,h.Fit),m.FHD=new n("fhd",1920,1080,h.Fit),m.HD=new n("hd",1280,720,h.Fit),m.WVGA=new n("wvga",720,480,h.Fit),m.QVGA=new n("qvga",320,240,h.Fit),m.QQVGA=new n("qqvga",160,120,h.Fit),m.S480=new n("s480",480,480,h.Square),m.S240=new n("s240",240,240,h.Square),m.S120=new n("s120",120,120,h.Square),m.S60=new n("s60",60,60,h.Square)},87062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const n=i(4866),r=i(11944),s=i(61570),a=i(7162),o=i(7383),l=i(43414),u=i(96593),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),n=i?.capturedAt;null!=n&&(delete i.capturedAt,(0,s.assignFields)(i,n.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},58061:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=n(i(57441)),s=i(1429),a=i(39784),o=i(81108),l=i(6667),u=i(72461);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,n)=>t>=(0===n?e[i]:n%i==0?e[n-i]:e[n-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),n=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(n.map(c)),diffHash:(0,s.flatten)(n.map(d))}}},35254:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const n=i(4866),r=i(18941),s=i(98250),a=i(7162),o=i(43414),l=i(13378),u=i(27446),c=i(49441),d=i(87062),h=i(23024),f=i(14489),m=(0,n.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=s.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},19371:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const n=i(4866),r=i(66776),s=i(7162),a=i(13378),o=i(82341),l=i(65564),u=i(8104);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,n.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},36143:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(11944),r=i(57743),s=i(75556),a=i(8199),o=i(13779),l=i(70283);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},53026:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(4866),r=i(75556),s=i(31737),a=i(7162),o=i(14889),l=i(69317),u=i(79015),c=i(84571),d=i(22143),h=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},80870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const n=i(4866),r=i(57743),s=i(85643),a=i(9381),o=i(75556),l=i(61570),u=i(84253),c=i(7162),d=i(34928);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,n.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,n){const r=(0,d.lteBoth)(e,n)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(n,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},23024:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(57441)),s=i(4866),a=i(7162),o=i(43414),l=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function u(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){l().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return u(t,i)}catch(e){return l().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=u,t.sharpRenderOptions=function(){return{quality:o.Settings.previewQuality.valueOrDefault,progressive:o.Settings.previewProgressive.valueOrDefault,mozjpeg:o.Settings.previewMinimized.valueOrDefault}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},14489:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(889),s=n(i(57441)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(57743),d=i(87748),h=i(75556),f=i(61570),m=i(44726),p=i(50530),g=i(7162),y=i(70283),v=i(46852),w=i(7383),S=i(79141),b=i(98250),P=i(95725),M=i(43414),_=i(96593),x=i(27446),E=i(84685),T=i(15465),D=i(68107),k=i(53719),C=i(59387),F=i(34928),O=i(71923),I=i(49312),L=i(49441),A=i(23024),R=i(46517),N=i(50885),B=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable"))),z=(0,a.lazy)((()=>{s.default.simd(M.Settings.enableSIMD.valueOrDefault),s.default.cache(M.Settings.enableVipsCache.valueOrDefault),s.default.concurrency((0,C.sharpThreadsPerProcess)())}));async function j(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await W(e,t))?.nativePath}async function V(e,t,i,n,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void B().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=j,t.imgFromExif_=V,t.toSharp=function(e){const t=e;if((0,A.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const n=B().addParameterContext(e.nativePath);z();const s=await(0,T.readMimeType)(e);if((0,u.blank)(s))return n.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void n.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,x.isVideoMimeType)(s),b=(0,x.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return n.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:b,isVideo:g});const C=(0,F.aspectRatio)(a.fileDimensions),L=(0,h.lt)(C,1),A=(0,x.isSharpMimeType)(s)&&null==t,j=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||L||A||j)n.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:L,isSharpMimeAndNoMinDim:A,isMirrorOrientation:j});else{const i=!1,s=await(0,_.readRawTags)(e,i);if(null==s)n.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof r.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){n.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>V(e,s,t,k,C)))}}}(0,x.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,I.isHeifMimeType)(s)&&await(0,O.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,O.heif2img)(e),(e=>({file:e}))))),b&&f("raw2tiff",(()=>(0,v.thenMap)((0,N.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,R.isVideoSupported)())try{return await(0,v.thenMap)((0,R.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new S.WrappedError("Failed to extract video frame for "+e,t)}else n.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return n.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...r};n.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){n.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new S.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=W},59430:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.syncFileTimeout=t.dcrawTimeout=t.syncFileTimeoutForFile=t.syncFileTimeoutForFileMs=t.BytesPerSecond=t.MinSyncFileTimeoutMs=void 0;const n=i(43649),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=i(14889),u=i(46852),c=i(27947),d=i(96593),h=i(63526),f=i(53719);t.MinSyncFileTimeoutMs=r.minuteMs,t.BytesPerSecond=o.KB;const m={p0:{x:.8*o.MB,y:4*r.secondMs},p1:{x:20*o.MB,y:12*r.secondMs}},p={p0:{x:11*o.MB,y:12*r.secondMs},p1:{x:26*o.MB,y:24*r.secondMs}};function g(e){return(0,u.thenMap)(function(e){return(0,u.thenMap)(e.size(),(async t=>({bytes:t,ext:e.ext,durationMs:(0,h.isVideoExt)(e.ext)?(0,c.extractDurationMs)(await(0,d.readRawTags)(e,!1)):void 0})))}(e),y)}function y(e){if((0,h.isVideoExt)(e.ext))return{result:0};const i=l.ShortCommandTimeoutMs,r=(0,f.commandTimeoutMs)(),s=e.bytes/f.MinIoRate,u=t=>(0,n.lerp2d)((0,a.clamp)(.5*o.MB,50*o.MB,e.bytes),t.p0,t.p1),c=u(m),d=(0,h.isRawImageExt)(e.ext)?u(p):0;return{result:Math.max(t.MinSyncFileTimeoutMs,i+r+s+c+d),dbMs:i,tagMs:r,copyMs:s,thumbMs:c,rawDecodeMs:d}}t.syncFileTimeoutForFileMs=function(e){return(0,u.thenMap)(g(e),(e=>e.result))},t.syncFileTimeoutForFile=g,t.dcrawTimeout=function(e){return(0,n.lerp2d)((0,a.clamp)(11*o.MB,100*o.MB,(0,s.orElse)(e,0)),p.p0,p.p1)},t.syncFileTimeout=y},31216:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=n(i(57441)),s=i(4866),a=i(39938),o=i(88491),l=i(87748),u=i(7162),c=i(13378),d=i(91464),h=i(79141),f=i(21084),m=i(98250),p=i(95725),g=i(43414),y=i(27446),v=i(15465),w=i(53719),S=i(23024),b=i(14489),P=i(46517),M=i(15299),_=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),n=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(n)&&_().throw(n,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const x=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return x().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:x,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,b.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,S.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},33185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(4866),r=i(11944),s=i(43947),a=i(7162),o=i(1058),l=i(10408),u=i(43414),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},46517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(4866),r=i(11944),s=i(38625),a=i(88491),o=i(43947),l=i(85643),u=i(75556),c=i(8199),d=i(7162),h=i(19658),f=i(70283),m=i(13378),p=i(91464),g=i(3917),y=i(34996),v=i(7383),w=i(21142),S=i(79015),b=i(21084),P=i(98250),M=i(95725),_=i(43649),x=i(6667),E=i(49586),T=i(43414),D=i(68567),k=i(27947),C=i(96593),F=i(27446),O=i(84685),I=i(68107),L=i(53719),A=i(7218),R=i(49441),N=i(12737),B=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function z(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function j(e){return h.isProd&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,N.ffmpegVersion_)()}function V(e,i){const n=z("extractMaxBitrate",e),r=T.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,D.extractBitrateKbps)(i)??T.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}t.getVideoToolDetails_=j,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await j())?.isSupportedVersion}catch(e){return B().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,_.lerp2d)(e,{x:76800,y:T.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:T.Settings.transcodeBitrateUHD.valueOrDefault}),2);const W=(0,n.lazy)((()=>new b.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function H(e,t){const i=z("extractVideoFrame",e),n=P.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,N.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,R.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,C.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,I.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,A.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,k.extractDurationSec)(l),m=Math.min(f??0,T.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,N.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,C.deleteAllTags_)(e,e)},timeoutMs:(0,L.commandTimeoutMs)()}),r.nativePath}async function q(){return T.Settings.transcodeVideos.valueOrDefault&&await(0,N.isFFmpegSupported)()}async function G(e){const t=z("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,C.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,F.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,k.extractDurationSec)(i);if(!(0,c.gt)(s,T.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(T.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:W,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=q,t.needsTranscoding=G;const $=new g.TTLMap(15*a.minuteMs);function J(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,t,i){if(!await q())return;const n=z("transcode",e),r=$.get(t.nativePath);if(null!=r&&!(0,s.isTrue)(i?.force))return n.info("already transcoding",{dest:t,priorSrc:r.name}),r.promise.then((()=>t));const a=new y.Deferred(e.nativePath);if($.set(t.nativePath,a),!1===await G(e))return void n.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return n.throw("source is empty or cannot read");const d=await(0,C.readTags)(e);if(null==d)return n.throw("source cannot be read by ExifTool");if(!0===i?.force)await t.unlink();else if(await async function(e,t){const i=await(0,C.readRawTags)(t),n=await(0,C.readRawTags)(e),r=(0,k.extractDurationSec)(n),s=(0,k.extractDurationSec)(i);return B().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,t))return n.info("no-op, dest duration looks reasonable",{dest:t}),t;return(0,v.time)("video.transcode()",(async()=>{const i=(0,k.extractDurationSec)(d)??60,r={src:e,...V(e,d)},s=J(o,r.videoBitrateKbps,i),a=T.Settings.transcodeMaxDim.valueOrDefault,h=(0,x.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(a)&&(0,c.gt)(h,a)){const e=(0,l.fitInside)(d.dimensions,{width:a,height:a});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:a}):(r.width=(0,u.roundEven)(e.width),r.height=(0,u.roundEven)(e.height),n.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}return await t.applyWip_({fn_:i=>(async i=>{n.info("starting...",{destWip:i});const a=new E.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},s,(async()=>await t.clear().size()??0));r.dest=i,r.fps=(0,u.toGt0)(d.VideoFrameRate);const o=await a.observe((0,N.ffmpegTranscode_)(r));0!==o.code&&n.throw("transcode failed with code "+o.code)})(i),skipFsLock:!1,timeoutMs:0}),t}))},t.guessExpectedSize=J,t.validVideo_=async function(e){return null==await U(e)&&z("validVideo",e).throw("Could not extract a video frame"),(0,N.ffmpegValidVideo_)(e)}},12737:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(11944),r=i(39938),s=i(38625),a=i(88491),o=i(43947),l=i(75556),u=i(82798),c=i(4866),d=i(7162),h=i(70283),f=i(46852),m=i(21142),p=i(69317),g=i(10408),y=i(79015),v=i(9288),w=i(74836),S=i(43414),b=i(49849),P=i(53719),M=i(33185),_=i(5023),x=(0,c.lazy)((()=>(0,d.mkLogger)("img.ffmpeg")));function E(){return(0,v.pathTo)({tool:"ffmpeg",alternativePath:S.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=E;const T=/ffmpeg version n?(?\S+)/i,D=(0,c.lazy)((async()=>{const e=await E();if(null==e)return void x().info("failed to find ffmpeg in $PATH",{ffmpegPath:S.Settings.ffmpegPath.valueOrDefault});const t=await(0,p.stdoutResult_)(e,["-version"],{timeoutMs:(0,P.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return x().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){D.unset(),t.ffmpegVersionDescription.unset()}function C(e){const t=e?.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function F(e){const t=[...S.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(S.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function O(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function I(e){const t=S.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,c.lazy)((()=>(0,f.thenMapOr)(D(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,y.ee)().on("clearCache",k),(0,y.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.isFFmpegSupported=async function(){return null!=await D()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,...(0,h.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:M.isIgnorableValidationError}),!await(0,m.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=F,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,p.stdoutResult_)(await E(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...F(t),...I(t),...C(t),"-threads",(0,u.toS)((0,_.ffmpegThreads)()),...O(t.videoBitrateKbps),t.dest.nativePath]),{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError})}catch(i){x().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const n=(0,g.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??S.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return x().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return x().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,p.stdoutResult_)(await E(),["-v","error","-nostats","-i",e.nativePath,"-threads",(0,u.toS)((0,_.ffmpegThreads)()),"-f","null","-"],{timeoutMs:0,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},5023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegThreads=void 0;const n=i(75556),r=i(4866),s=i(43414),a=i(59387);t.ffmpegThreads=(0,r.lazy)((()=>(0,n.toGt0)(s.Settings.ffmpegThreads.value)??(0,n.clamp)(1,6,(0,n.round)((0,a.maxCpus)()/4))))},15299:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const n=i(4866),r=i(88491),s=i(33714),a=i(7162),o=i(69317),l=i(79141),u=i(98250),c=i(22143),d=i(51053),h=i(53719),f=i(33185),m=d.isWin?"NUL":"/dev/null",p=(0,n.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const n=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(n,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},50885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(57743),o=i(17078),l=i(22840),u=i(82798),c=i(7162),d=i(69317),h=i(10408),f=i(53525),m=i(79141),p=i(22143),g=i(49586),y=i(43414),v=i(27446),w=i(15465),S=i(7218),b=i(49441),P=i(36810),M=i(59430),_=i(33185),x=(0,n.lazy)((()=>(0,c.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,v.isLibrawMimeType)(await(0,w.readMimeType)(e.nativePath))}catch(t){return x().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,b.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>C(e,t)})};const E=["-T"],T=["-Z","-"],D=["-o","1"],k=["-t","0","-j"];async function C(e,t){const i=Date.now(),n=await(0,S.dimensions)(e);if(null==n)return x().throw("Cannot decode RAW "+e+": no EXIF dimensions."+f.DoNotSendErrorFlag+f.NonRetriableErrorFlag);const c=P.ImageSize.largestFit().outputSize(n),v=[];null!=c&&4*(0,a.dmegapixels)(c)<(0,a.dmegapixels)(n)&&(x().debug("Large original source: using -h"),v.push("-h"));const w=await(0,p.dcrawEmuNativePath_)(),b=[...E,...T,...D,...v,...k,...y.Settings.dcrawEmuArgs.values,e.nativePath],C=5*s.minuteMs,F={encoding:"buffer",timeout:C,maxBuffer:250*o.MB};x().debug("dcraw_emu()",{cmd:w,args:b,opts:F});const O=(0,d.execFile)(w,b,C,F),I=[];function L(t){const i=(0,l.isError)(t)?(0,h.errorToS)(t):(0,u.toS)(t);if((0,_.isIgnorableValidationError)(i))x().info("dcraw_emu(): warning",{src:e,msg:i});else{x().warn("dcraw_emu(): error",{src:e,msg:i});const n=(0,l.isError)(t)?t:(0,m.toWrappedError)(i,{fatal:!1});I.push(n)}}O.on("error",L),O.stderr.on("data",L);const A=(0,M.dcrawTimeout)(await e.size())/7,R=new g.PullProgressObserver({path:e.nativePath,op:"Converting raw image"},A,(()=>Date.now()-i));if(O.on("close",(()=>R.end())),await t.writeStream_(O.stdout),(0,r.isNotEmpty)(I))throw new m.WrappedError("Failed to convert RAW image "+e,{causes:I,path:e.nativePath});(0,d.endProcess)(O)}t.dcraw_emu_=C},16114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(4866),r=i(69317),s=i(9288),a=i(51053),o=i(43414),l=i(53719),u=i(49441);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},14235:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(47261),r=i(4866),s=i(11944),a=i(39938),o=i(82798),l=i(26302),u=i(19658),c=i(55568),d=i(43414),h=i(95976),f=i(48924),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={showHidden:!1,depth:5,colors:!0,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},u.isTest&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),a=i(98968);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),a=i(61570),o=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,o.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},4785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(7162),r=i(81026);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},88777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(43947),o=i(87748),l=i(66776),u=i(75556),c=i(61570),d=i(9678),h=i(55568),f=i(91464),m=i(10408),p=i(9483),g=i(48924),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},7258:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(87503),a=i(4866),o=i(39938),l=i(88491),u=i(43947),c=i(87748),d=i(6314),h=i(75556),f=i(91641),m=i(95557),p=i(7162),g=i(99869),y=i(43414),v=i(88777),w=i(98741),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},81647:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(49411),r=i(88491),s=i(43414);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),a=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},98741:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const s=i(4866),a=i(11944),o=i(39938),l=i(82798),u=i(43414),c=i(95976),d=i(9483);t.LogFilterImpl=class{constructor(e=u.Settings.logLevel){this.setting=e,this.silent=!1,this.contexts=[],n.set(this,(0,s.lazy)((()=>{this.contexts.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=d.LogLevels.indexOf(e)??d.LogLevels.indexOf(this.setting.defaultValue)??d.LogLevels.indexOf(d.LogLevels.warn);const t=(0,a.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,l.toS)(t[1]).toLowerCase(),i=(0,d.levelIndex)(t[2]);(0,o.blank)(e)?this.defaultLevelIndex=i:this.contexts.push({prefix:e,levelIndex:i})}}}))),e.watch((()=>r(this,n,"f").refresh()))}contextOverride(e){if(null==e||0===this.contexts.length||(0,o.blank)(e))return;const t=(0,l.toS)(e).toLowerCase();return this.contexts.find((e=>t.startsWith(e.prefix)))}enabled(e,t){if(this.silent)return!1;const i=(0,d.levelIndex)(e);if(null!=t){const e=this.contextOverride(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.contextOverride(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},48924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(11944),r=i(61570),s=i(26588),a=i(44726),o=i(22840),l=i(13779),u=i(2023),c=i(10408),d=i(43414);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"โ€ฆ";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`โ€ฆ (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("โ€ฆ"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["โ€ฆ"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},55248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(87561),r=i(49411),s=i(97742),a=i(92332),o=i(4866),l=i(39938),u=i(88491),c=i(21040),d=i(66776),h=i(8199),f=i(26588),m=i(19658),p=i(55568),g=i(97198),y=i(58623),v=i(31329),w=i(91641),S=i(95557),b=i(4691),P=i(70259),M=i(80294),_=i(10408),x=i(57400),E=i(3955),T=i(43414),D=i(71951),k=i(85352),C=i(81647),F=i(95976),O=i(9483),I=i(98968),L=i(53208);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);m.isTest&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await x.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(O.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e,t)))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues.",e)))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await x.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),a=i(85352),o=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},81026:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(87561)),f=i(49411),m=i(4866),p=i(88491),g=i(43947),y=i(87748),v=i(75556),w=i(99869),S=i(55568),b=i(91464),P=i(28807),M=i(91641),_=i(93033),x=i(40374),E=i(83837),T=i(43414),D=i(74269),k=i(85352),C=i(81647),F=i(95976),O=i(48924),I=i(94679);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:F.logFilter,...t},this.onEnds.push((()=>c(this,r,"f").call(this))),this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,O.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,x.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),a=i(61570),o=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},53208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(39938),r=i(51081),s=i(81666),a=i(95998),o=i(77200);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},94679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(4866),r=i(59694),s=i(61570),a=i(24945),o=i(9483);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},4657:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(49411),r=i(4866),s=i(66776),a=i(26302),o=i(12374),l=i(7162),u=i(36079),c=i(1629),d=i(35796),h=i(29405),f=i(20902),m=i(47987),p=i(43414),g=i(14235),y=i(74269),v=i(4785),w=i(71951),S=i(7258),b=i(95976),P=i(98741),M=i(55248),_=i(81026),x=i(27998);t.setupLogger=(0,r.lazy)((()=>{(0,b.logFilter)()instanceof P.LogFilterImpl||b.logFilter.set(new P.LogFilterImpl),(0,t.setupLogFormatter)();const e=(0,d.logDir)();let i=(0,v.currentFileLogger)();null!=i&&i.logDir===e||((0,u.end)(i),(0,m.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),i=new _.LogWriter(e));const r=[i];((0,f.isEnvTrue)("logStdout")||p.Settings.logStdout.valueOrDefault||p.Settings.tailLogs.valueOrDefault)&&r.push(y.ConsoleLogger.instance()),(0,s.map)((0,S.logBroadcaster)(),(e=>r.push(e))),l.rootLoggers.set(r),p.Settings.tailLogs.valueOrDefault&&M.LogTail.instance(),p.Settings.logLevel.watchLater((()=>b.defaultLogLevel.unset())),(0,a.setColorEnabled)(p.Settings.logColor.valueOrDefault),(0,c.cacheDir)(),E(),(0,o.addDefaultJsonRevivers)()})),t.setupLogFormatter=(0,r.lazy)((()=>{const e=(0,w.DefaultLogFormatter)()instanceof g.ColoredLogFormatter,t=null==(0,h.env)().NO_COLOR&&p.Settings.logColor.valueOrDefault;e!==t&&w.DefaultLogFormatter.set(t?new g.ColoredLogFormatter:new x.PlaintextLogFormatter)}));const E=(0,r.lazy)((()=>{p.Settings.logStdout.watchLater((()=>t.setupLogger.refresh())),p.Settings.logDir.watchLater((()=>t.setupLogger.refresh())),p.Settings.tailLogs.watchLater((()=>t.setupLogger.refresh())),p.Settings.logColor.watchLater((()=>t.setupLogFormatter.refresh()))}))},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(47261),o=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,o.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),a=i(23175),o=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},25506:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const n=i(59694),r=i(89965);t.kmeans=function(e,t,i){const s=r(e,t,i);return{...s,centroids:(0,n.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},71538:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const n=i(11944),r=i(75556),s=i(13779),a=i(60346),o=i(6667);function l(e,t,i,n){const r=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,n){const s=new a.Average;return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,n){const s=[];return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,n.range)(r,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,n=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:n/2}),u(e,t,{col:0,row:0},{col:i/2,row:n/2}),u(e,t,{col:0,row:n/2},{col:i/2,row:n}),u(e,t,{col:i/2,row:n/2},{col:i,row:n})];return(0,s.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,n=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:n/2}),c(e,t,{col:0,row:0},{col:i/2,row:n/2}),c(e,t,{col:0,row:n/2},{col:i/2,row:n}),c(e,t,{col:i/2,row:n/2},{col:i,row:n})])},t.greatestHalf=function(e,t){const i=t.col,n=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:n/2}),d(e,t,{col:0,row:0},{col:i/2,row:n}),d(e,t,{col:0,row:n/2},{col:i,row:n}),d(e,t,{col:i/2,row:0},{col:i,row:n})];return(0,s.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const n=[];return l(e,t,i,(e=>n.push(e))),n},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,n.stepRange)(0,t.row,u,(i=>(0,n.stepRange)(0,t.col,o,(n=>(c.clear(),l(t,{col:n,row:i},{col:n+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),a=i(47025),o=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},17208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(75556),r=i(82798);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},48446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const n=i(65628),r=i(39938),s=i(70283);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,n.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,n.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),a=i(39938),o=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),a=i(98510),o=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},95487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(11944),r=i(39938),s=i(43383),a=i(39784),o=i(7162),l=i(55463),u=i(69317),c=i(51081),d=i(49849),h=i(53719),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),a=i(60052),o=i(51053);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},79621:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(43383),r=i(7162),s=i(69317),a=i(63410),o=i(53719),l=i(51053),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),a=i(39938),o=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),a=i(51053);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},86780:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const n=i(39938),r=i(44726),s=i(63774);t.negateFilterName=function(e){if((0,n.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},38336:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const n=i(4866),r=i(11944),s=i(61570),a=i(7162),o=i(86780),l=(0,n.lazy)((()=>(0,a.mkLogger)("predicates.Predicates")));class u{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i))if(!1===await t(e))return!1;return!0}static async rejected(e,...t){return!await u.accepted(e,...t)}static async explain(e,...t){const i=[],n=[],r=[];for(const a of t)for(const[t,o]of(0,s.entries)(a)){const s=await o(e);!0===s?i.push(t):!1===s?n.push(t):r.push(t)}return{accepted:i,rejected:n,notApplicable:r}}static async whyRejected(e,...t){return(0,o.negateFilterName)(await u.firstFalse(e,...t))}static async firstFalse(e,...t){for(const i of t)for(const[t,n]of(0,s.entries)(i))try{if(!1===await n(e))return t}catch(e){l().warn("firstFalse() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:n}){const{accepted:s,rejected:a}=await u.explain(e,...n);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=u},51776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const n=i(61570),r=i(86780);class s{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),a=i(3955),o=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),a=i(13378),o=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),a=i(28807),o=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},4416:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const n=i(75556),r=i(29663);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,n.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,n.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),M=i(51053),_=i(43414),x=i(53719),E="{ready}",T=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,x.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,x.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),a=i(84161);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},47874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const n=i(38625),r=i(61570),s=i(84253),a=i(43414),o=(0,s.strEnum)("forceSync","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags");t.pickForceContext=function(e){return(0,r.pick)(e,...o.values)},t.forceContextOrSetting=function(e){return(0,r.fromEntries)(o.values.map((t=>[t,e?.[t]??(0,n.isTrue)(a.Settings[t]?.valueOrDefault)])))}},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},23830:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.allowFilesystemSleep=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(4866),r=i(39938),s=i(38625),a=i(88491),o=i(75556),l=i(61570),u=i(44726),c=i(7162),d=i(70283),h=i(18226),f=i(48995),m=i(18947),p=i(92438),g=i(43414),y=i(96879),v=(0,n.lazy)((()=>(0,c.mkLogger)("settings.MetaSettings")));function w(e,t){return g.Settings[e].value??t.find((t=>t.name===e))?.value??g.Settings[e].defaultValue}function S(){g.Settings.respectFileExtensions.envValue=!1,g.Settings.requireMakeModel.envValue=!1,g.Settings.rejectRatingsLessThan.envValue=-100,g.Settings.minImageDimension.envValue=0,g.Settings.minVideoDimension.envValue=0,g.Settings.minVideoDurationSec.envValue=0,g.Settings.maxVideoDurationSec.envValue=0,g.Settings.minAssetFileSizeBytes.envValue=0,g.Settings.maxAssetFileSizeBytes.envValue=0,g.Settings.validateJpegImages.envValue=!1,g.Settings.validateRawImages.envValue=!1,g.Settings.validateVideos.envValue=!1}function b(){g.Settings.strictDeduping.envValue=!0,g.Settings.useImageHashes.envValue=!0,g.Settings.minExposureSettingsCoeffPct.envValue=98,g.Settings.minImageCoeffPct.envValue=95,g.Settings.imageHashFuzzyDateDelta.envValue=1,g.Settings.imageHashDifferentMimetypesDelta.envValue=-10,g.Settings.imageHashGreyscaleDelta.envValue=1}function P(){g.Settings.sharedStatePollMs.envValue=0}t.handleMetaSettings=function(e){E(g.Settings.quickSyncMode.valueOrDefault),w("disableAllFilters",e)&&S(),w("strictDeduping",e)&&b(),w("allowFilesystemSleep",e)&&P(),w("optOut",e)&&T()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(g.Settings.scanMyPictures.value)){g.Settings.scanMyPictures.unset();const e=await(0,h.picturesDir)();v().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:g.Settings.scanPaths.values,newPath:e}),g.Settings.scanPaths.push(e)}{const e=g.Settings.assetSubdirectoryDatestampFormat.value;if(g.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(g.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,u.ensureSuffix)(e,"/")+"BASE";v().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),g.Settings.assetPathnameFormat.value=t}}{const e=g.Settings.syncIntervalHours.value;g.Settings.syncIntervalHours.unset();const t=(0,d.mapGt0)(e,(e=>e*a.hourMs));!g.Settings.syncNewIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncNewIntervalMs",{prior:e,newValue:t}),g.Settings.syncNewIntervalMs.value=t),!g.Settings.syncChangedIntervalMs.hasValue()&&(0,o.gt0)(t)&&(v().info("Upgrading setting syncIntervalHours to syncChangedIntervalMs",{prior:e,newValue:t}),g.Settings.syncChangedIntervalMs.value=t)}if(g.Settings.dbBackupIntervalMinutes.hasValue()&&!g.Settings.dbBackupIntervalMs.hasValue()){const e=g.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;v().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),g.Settings.dbBackupIntervalMs.value=e}if(g.Settings.siblingInferenceBasenameCoeff.hasValue()&&!g.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*g.Settings.siblingInferenceBasenameCoeff.valueOrDefault);v().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),g.Settings.siblingInferenceBasenameCoeffPct.value=e}if(g.Settings.enableSiblingInference.hasValue()&&!g.Settings.siblingInference.hasValue()){const e=g.Settings.enableSiblingInference.valueOrDefault?g.Settings.siblingInference.valueOrDefault:y.TagInferenceSettingValues.never;v().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),g.Settings.siblingInference.value=e}},t.disableAllFilters=S,t.setStrictDeduping=b,t.allowFilesystemSleep=P;const M=[g.Settings.validateJpegImages,g.Settings.validateRawImages,g.Settings.validateVideos,g.Settings.transcodeVideos,g.Settings.previewMinimized,g.Settings.previewProgressive,g.Settings.previewSharpen,g.Settings.useImageHashes,g.Settings.enableSiblingInference],_={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},x={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function E(e){for(const t of M)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?x:_;for(const[e,i]of(0,l.entries)(t))g.Settings[e].defaultValue=i;g.Settings.dominantColorPixels.defaultValue=e?256:p.DominantColorPixelsDefault,g.Settings.dominantColorKmeansRuns.defaultValue=e?0:m.DominantColorKmeansRunsDefault,g.Settings.dominantColorDeltaE.defaultValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function T(){g.Settings.autoUpdateCheck.defaultValue=!1,g.Settings.allowUserAgent.defaultValue=!1,g.Settings.reportErrors.defaultValue=!1}t.setQuickSyncMode=E,t.disableExternalNetworkRequests=T},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),a=i(24603),o=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),M=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,a.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],M.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,o.orList)(i.map((e=>(0,l.stringify)(e))))],M.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,o.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],M.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:M.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),M=i(27387),_=i(29393),x=i(94794),E=i(7560),T=i(45005),D=i(20902),k=i(6565),C=i(80534),F=i(86613),O=i(15203),I=i(51053),L=i(33407),A=i(11579),R=i(82590),N=i(55267),B=i(98788),z=i(61659),j=i(40185),V=i(32994),W=i(39036),U=i(86115),H=i(36738),q=i(17679),G=i(75153),$=i(1440),J=i(92187),K=i(79660),Z=i(29712),X=i(26764),Y=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),ae=i(23753),oe=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>I.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:q.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!I.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>I.isMac?"100ms":I.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new X.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new X.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:_.CheckpointTypes,defaultValue:_.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:E.SynchronousModes,defaultValue:E.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new X.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,O.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:I.isWin?["proc-not-superuser"]:[],strEnum:k.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>I.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:Y.ColorDistanceFunctions.ciede2000,strEnum:Y.ColorDistanceFunctions}),dominantColorKmeansRuns:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new X.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new X.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:C.CropStrategies.attention,strEnum:C.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(I.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:J.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>N.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ae.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new oe.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:R.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>B.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new X.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:j.NameTagFormats["as-is"],strEnum:j.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:V.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,D.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,o.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),a=i(4586),o=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=a.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?o.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},82041:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(88491),l=i(43947),u=i(24603),c=i(16475),d=i(1429),h=i(51367),f=i(87748),m=i(66776),p=i(61570),g=i(65113),y=i(44726),v=i(82798),w=i(7162),S=i(91464),b=i(63774),P=i(42041),M=i(82341),_=i(10408),x=i(79015),E=i(98462),T=i(98250),D=i(38846),k=i(23830),C=i(84161),F=i(44911),O=i(43414),I=i(95699),L=i(85560),A=i(98024),R=i(13060),N=i(31086),B=i(16704),z=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,M.libraryDataDirPosixFile)(e)?.join(L.SettingsToml)}async function V(e=(0,A.systemSettingsFile)()){if(null!=e)return Q(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,R.readTomlFile_)((0,A.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}async function U(){return J((0,A.systemSettingsFile)())}async function H(e){return(0,m.map)(j(e),(e=>J(e)))}function q(){t.libraryHasSettings.refresh()}function G(e){const t=j(e);return z().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await X()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){P.version!==await U()&&await Z()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&P.version!==await H()&&await Y()},t.libraryHasSettings=(0,n.lazy)((()=>G())),t.libraryHasSettings.unset=()=>{z().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,x.ee)().on("clearCache",q),(0,x.ee)().on("settingsChanged",q),O.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=G;const $=/^# PhotoStructure v(?\d+\.\d+\.\d+(?:-\S+)?)$/i;async function J(e){if((0,a.blank)(e))return;const t=await E.BaseFile.for(e).firstMatchingLine($);return t?.groups?.version}async function K(e,i){if(null==e)return void z().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ne("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","-- ","","PhotoStructure v"+(0,t.versionForSettings)())),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,x.ee)().emitDebounced("settingsChanged")}(r,i),z().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,C.settingsToObj)(i),wip:n}),n){const t=await(0,R.readTomlFile_)(r),i=await(0,R.readTomlFile_)(e);(0,u.eql)(t,i)?(z().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(z().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"old"}),await r.unwip_())}}async function Z(e=(0,A.systemSettingsFile)()){const t=T.PosixFile.forMaybe(e);return null!=t&&await K(t,(0,O.persistedSystemSettings)()),t}function X(e){return Q(j(e))}async function Y(e){await(0,M.setupLibraryDataDir_)((0,a.firstNotBlank)(e,O.Settings.libraryDir.value));const i=j(e);return z().info("writeLibrarySettings()",{file:i}),null!=i&&(await K(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Q(e){if(null==e)return[];const t=z().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await ee(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function ee(e){const t=z().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,R.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{if(null!=i.normalizeValue(t))return i.fileValue=t,i;s.push(`Invalid value for "${e}": ${(0,f.stringify)(t)}`)}})));return t.info("loaded",{settings:(0,C.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:s}}t.versionForSettings=(0,n.lazy)((()=>P.version)),t.writeSystemSettings_=Z,t.writeAllSettings_=function(e){return K(T.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=X,t.writeLibrarySettings_=Y,t._readSettings=Q,t.importFileSettings_=ee;const te=(0,n.lazy)((()=>new Set([O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function ie(){for(const e of(0,p.values)(O.Settings))te().has(e.key)||e.unset();(0,x.ee)().emit("settingsChanged")}function ne(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),O.Settings.libraryDir.unset(),await Z()},t.clearSettings=ie,t.nukeSettings=async function(){ie(),await(T.PosixFile.forMaybe((0,A.systemSettingsFile)())?.unlink("trace")),await(T.PosixFile.forMaybe(j())?.unlink("trace")),(0,x.ee)().emit("clearCache"),I.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ne("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ne("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ne("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ne("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ne((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),a=i(87748),o=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,a.stringify)(e)}t._join=c;function d(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),a=i(70338);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),a=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),a=i(83486),o=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),a=i(61570),o=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},31086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(87748);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},68567:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(82798),r=i(70283);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},65642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(88491),u=i(24603),c=i(87748),d=i(66776),h=i(75556),f=i(61570),m=i(82798),p=i(13779),g=i(7162),y=i(91464),v=i(80294),w=i(76387),S=i(85590),b=i(45161),P=i(23595),M=i(46175),_=i(50140),x=i(68074),E=i(54809),T=i(64455),D=i(60299),k=i(3955),C=i(95725),F=i(63410),O=i(9483),I=i(43414),L=i(69301),A=i(82590),R=i(63526),N=i(26352),B=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function j(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function V(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,w.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=j,t.isCapturedAtJson=V;class W{static fromAssetFile(e){return(0,d.map)((0,x.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>W.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof W?e:V(e)?new W(e):void 0}constructor(e){this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=e.src,this.local=(0,h.toGt0)(e.local)??(0,x.datedToLocal)(this.date),this.offset=e.offset??(0,b.datedToOffsetMinutes)(this.date);let t=(0===e.precisionMs?void 0:e.precisionMs)??(0,w.datedToPrecisionMs)(this.date);j(this.src)&&(t=Math.max(I.Settings.minCapturedAtPrecisionStat.valueOrDefault,t)),this.precisionMs=t,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:W.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,P.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,E.fmtOffsetMinutes)});return null==t?void 0:new W({...e,date:t})}spread(e){return new W({...this.toJSON(),...e})}toISOString(){return(0,b.datedToISO)(this.date)}toExifString(){return(0,b.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,E.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!j(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,x.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,b.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (ยฑ"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,D.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,_.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,T.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,D.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,E.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?I.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,w.datedToStartDateTime)(this.date)??(0,w.datedToDateTime)(this.date);if(null!=i)return{start:(0,x.datedToLocal)(i.minus(t)),end:(0,x.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,R.extMimetype)(this.nativePath)===(0,R.extMimetype)(e.nativePath)?0:I.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,w.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>W.for(e))));for(const n of t){let t=e[n],r=n;if((0,T.isValidDate)(t)){if((0,E.isValidZone)(e.tz)&&(!(0,D.hasZone)(t)||A.OverrideUTCZoneTags.includes(r))){t=(0,b.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,y.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,x.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,w.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,w.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,w.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,D.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function H(e,t){if(I.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,P.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,w.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(I.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,P.extractDateFromPath)(e.pathsForDateParsing)}}async function G(e){if(I.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("bname+stat")))??t.find((e=>e.src.includes("path+stat")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return V(i)?W.for(i):null!=i&&null!=i.date&&(0,T.isValidDate)(i.date)?W.for({nativePath:e.nativePath,date:i.date,local:(0,x.datedToLocal)(i.date),src:(0,y.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,b.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!I.Settings.usePathsToInferDates.valueOrDefault||!I.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,k.containedByNativePath)({ancestor:I.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,I.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,I.Settings.capturedAtTagsFallback.values))??(s?void 0:r("bname+stat",await(0,N.extractStatBname)(e)))??(s?void 0:r("path+stat",await(0,N.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,N.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",H(e,t)))??(s?void 0:r("path",q(e)))??(I.Settings.useStatToInferDates.valueOrDefault?r("stat",await G(e)):void 0);return B().tap({level:O.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,I.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=q,t.capturedAtFromStat=G},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},27947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(75556),r=i(70283),s=i(98250),a=i(96593),o=i(27446);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},96593:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(889),s=n(i(49411)),a=n(i(97742)),o=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(89253),f=i(61570),m=i(8199),p=i(44726),g=i(39784),y=i(82798),v=i(17078),w=i(7383),S=i(37121),b=i(13056),P=i(55170),M=i(45161),_=i(23595),x=i(84593),E=i(21084),T=i(98250),D=i(95725),k=i(76531),C=i(7162),F=i(76474),O=i(19658),I=i(2023),L=i(55568),A=i(43414),R=i(13378),N=i(14889),B=i(91464),z=i(53719),j=i(59387),V=i(65642),W=i(27947),U=i(74873),H=i(45581),q=i(94435),G=i(63526),$=i(31195),J=i(92330),K=i(71932),Z=i(91854),X=i(54988),Y=i(27446),Q=i(84685),ee=i(36062),te=i(15465),ie=i(68107),ne=i(26352),re=i(45023),se=(0,o.lazy)((()=>(0,C.mkLogger)("tags.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:A.Settings.backfillTimezones.valueOrDefault,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,...(0,b.batchClusterOptions)((0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():1,"tags.exiftool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeout)(le().version(),N.ShortCommandTimeoutMs,(()=>{throw new Error("ExifTool timed out")}))},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeout)(e.version(),(0,z.commandTimeoutMs)(),(()=>{throw new Error("ExifTool timed out")}))))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"tags.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,B.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const n=T.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(64))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("tag.parseTags()",(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,ne.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l),(0,f.assignFields)(s.inferred,l)}const c=o?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,o);if(null==h)return void se().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};O.isTest&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,x.eqlAsync)(e.sha(),t.sha())||await(0,x.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"tags.readTags",impl:async e=>{const t=T.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("tag.overwriteTags()",(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("tag.deleteAllTags()",(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("tags.writeTags",(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=T.PosixFile.for(t),r=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await fe(n)),A.Settings.overwriteOriginal.valueOrDefault||await he(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"tags.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=(0,G.isVideoExt)(s.default.extname(e))?[]:void 0,n=await(0,w.time)("tag.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),ae&&(n.__instance=(0,F.safeUUID)()),n}}),t.parseTags=ge},74873:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(87748),o=i(89253),l=i(75556),u=i(61570),c=i(2934),d=i(90957),h=i(82798),f=i(13779),m=i(85563),p=i(70283),g=i(91464),y=i(43414),v=i(91854);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function x({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" โ‰  "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>x({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>x({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>x({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>x({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},45581:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(39938),r=i(82798),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},94435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(4866),r=i(39938),s=i(75556),a=i(61570),o=i(82798),l=i(7162),u=i(70283),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),a=i(89253),o=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},31195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(889),r=i(4866),s=i(11944),a=i(59694),o=i(39938),l=i(24603),u=i(87748),c=i(75556),d=i(61570),h=i(84253),f=i(44726),m=i(39784),p=i(82798),g=i(9678),y=i(79378),v=i(7162),w=i(91464),S=i(85590),b=i(54809),P=i(3955),M=i(98250),_=i(95725),x=i(43414),E=i(96593);function T(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=T,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function O(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=F(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=O,t.ensureInferredHistoryRecords=async function(e,i,n){const r=T(t.Actions.infer,n),s=(x.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?O(n):void 0)??{};return x.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),I(i,r,s)},t.ensureHistoryRecords=I},92330:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(9160)),s=i(889),a=i(4866),o=i(11944),l=i(76387),u=i(45161),c=i(23595),d=i(54809),h=i(64455),f=i(85563),m=i(7162),p=i(2023),g=i(43414),y=i(69301),v=i(26352),w=(0,a.lazy)((()=>(0,m.mkLogger)("tags.InferTimezone")));async function S(e,t,i){{const e=b(t);if(null!=e&&(0,d.isValidZone)(e)){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,p.eqlSubset)(i,t)?void 0:i}}if(!(0,d.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,d.isValidZone)(i.zone)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=P(e,t);if(null!=i)return i}if(!i){const t=await(0,v.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function b(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,f.validLat)(t)||!(0,f.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i),n=(0,d.normalizeZone)(e);return w().tap({msg:"zoneFromLatLon()",result:n,meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function P(e,t){const i=(0,c.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,l.toDated)(t[n]);if(null==r||(0,h.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,d.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,d.normalizeZone)(a);if(null!=o)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,u.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i)})},t.zoneFromLatLon=b,t.inferTzOffsetMinutesFromFilename=P},71932:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(889),r=i(11944),s=i(39938),a=i(38625),o=i(66776),l=i(75556),u=i(61570),c=i(26588),d=i(39784),h=i(13779),f=i(85563),m=i(23595),p=i(54809);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},28033:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const n=i(889),r=i(25861),s=i(4866),a=i(11944),o=i(39938),l=i(43947),u=i(1429),c=i(61570),d=i(39784),h=i(13779),f=i(7162),m=i(1058),p=i(91464),g=i(43414),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function S(e){return null==e||e instanceof n.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(S)):w(e))}function b(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(b).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=S;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(b))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function x(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,x);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,x).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=x,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const n=M(e.Categories);null!=n&&t.push(...n)}for(const n of i){const i=(0,c.pluckDeep)(e,n)?.value;(0,o.blank)(i)||(_(i)?t.push(...x(i)):t.push(...Array.isArray(i)?i:S(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},91854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(66776),o=i(75556),l=i(61570),u=i(82798),c=i(13779),d=i(7162),h=i(43414),f=i(54988),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},54988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(61570),o=i(82798),l=i(1058),u=i(91464),c=i(17208),d=i(45581);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"ฮฑ").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},27446:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(39938),r=i(82798),s=i(39607),a=i(71923),o=i(49312),l=i(46517),u=i(63526),c=i(15465),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},84685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(33714),r=i(82798),s=i(27446);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},36062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(66776),r=i(75556),s=i(43414);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},15465:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(4866),r=i(39938),s=i(66776),a=i(21084),o=i(18941),l=i(98250),u=i(53719),c=i(96593),d=i(27446);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),a=i(91464),o=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isExt)(i.ext,"json"),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(n.length)),l=s(i.slice(n.length));return o&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},68107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(4866),r=i(39938),s=i(88491),a=i(57743),o=i(13779),l=i(7162),u=i(21084),c=i(98250),d=i(34928),h=i(53026),f=i(46517),m=i(27947),p=i(96593),g=i(27446),y=i(84685),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},26352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(889),r=i(42748),s=i(4866),a=i(11944),o=i(59694),l=i(39938),u=i(88491),c=i(66776),d=i(39784),h=i(13779),f=i(84593),m=i(7162),p=i(2073),g=i(7383),y=i(44665),v=i(76387),w=i(45161),S=i(23595),b=i(60299),P=i(85943),M=i(56640),_=i(21084),x=i(98250),E=i(75123),T=i(95725),D=i(9483),k=i(43414),C=i(96879),F=i(69301),O=i(65642),I=i(96593),L=i(17310),A=i(54988),R=i(27446),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function z(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await z(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7){if(!await z(e.parent()))return;const i=await(0,g.time)("tags.nearestSiblings",(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==i)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,o.sortBy)(i,(e=>(0,F.bname)(e))),r=(0,T.findFileIndex)(e,n);if(r<0)return void N().warn("nearestSiblings(): can't find self in siblings: "+e);const s=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[l,u]=[n.slice(r-2*t,r),n.slice(r+1,r+1+2*t)],c=[],d=[];for(;(0,a.isNotEmpty)(l)&&c.length=s&&c.push(t)}for(;(0,a.isNotEmpty)(u)&&d.length=s&&d.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:c,older:d},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await z(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},61473:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(66776),o=i(44726),l=i(39784),u=i(82798),c=i(13779),d=i(43414),h=i(91464);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,n.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,n.last)(e)):(0,n.last)(g(e))}function w(e,t){if((0,n.isEmpty)(e)||(0,n.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,n.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,n.uniqBy)((0,l.toA)(e),(e=>(0,n.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,n.compact)(t).map((e=>y(e))));return(0,n.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(n.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},45023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(11944),r=i(39938),s=i(61570),a=i(82798);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(1429),o=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),a=i(39938),o=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,o.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,o.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,o.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return x(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(x(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=x(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=x;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>T(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),a=i(49049),o=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),a=i(49049),o=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),a=i(49049),o=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(49411)),o=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),a=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},49849:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(10912),r=i(39938),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),a=i(51053),o=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),a=i(7162),o=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(39938),o=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function x(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(x(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(x(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(x(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=T,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function O(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function I(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(O)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=O,t.volumeInfoWin=I},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(88491),o=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),M=i(7903),_=i(55412),x=i(62255),E=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,x.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,E.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+E.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),a=i(7383),o=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),a=i(75556),o=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),a=i(39938),o=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),a=i(88491),o=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),M=i(95725),_=i(76531),x=i(51053),E=i(43414),T=i(39206),D=i(36736),k=i(62255),C=i(49829),F=i(10609),O=i(53719),I=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function R(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{E.Settings.libraryDir.watchLater(L),E.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");x.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),x.isLinux&&(await(0,k.maybeWatchProcMounts)(),await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await B()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*a.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",x.isWin?C.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return I().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(I().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(x.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,M.toNativePath_)(e);return x.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,P.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),L()})),E.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>R(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),R()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const B=(0,n.lazy)((async()=>{if(!x.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>R(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),a=i(13779),o=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await E()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function _(e){return!y.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function E(e=M,t=_,i=x){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),o=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=_,t.readProcMounts=E,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(M)?new h.FsWatcher({target:M,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+M),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),a=i(7162),o=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),a=i(81765),o=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||o.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||o.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||o.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||o.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),a=i(66776),o=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,a.orElse)(t,(()=>x())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const x=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(38625),o=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function _(e){return(0,a.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function x(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function E(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=x(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await E(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),w.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(_(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=_,t.toVolumeUUID=x,t.readUuidFile_=E,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),a=i(4866),o=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),M=i(55568),_=i(91710),x=i(14889),E=i(91464),T=i(46852),D=i(37121),k=i(1629),C=i(14195),F=i(42648),O=i(29405),I=i(20902),L=i(17875),A=i(79141),R=(i(79015),i(77390)),N=i(19653),B=i(3955),z=i(98250),j=i(95725),V=i(76531),W=i(18501),U=i(58659),H=i(15203),q=i(51053),G=i(43414),$=i(47044),J=i(69329),K=i(69551),Z=i(55412),X=i(11142),Y=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),ae=new Map,oe=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,$.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,ae),ue((0,$.volsha)(e.uuid),e,le),e}function de(){return(0,o.compact)([z.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),z.PosixFile.forMaybe((0,C.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Z.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ae.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Z.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,$.volsha)(e.uuid),(0,$.volsha)(e.mountpoint)]))s.set(t,e);const a=de();for(const e of a)await(0,N.withLock_)({file:e,timeoutMs:x.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,M.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(n))return;const r=await(0,R.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,B.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,E.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,M.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Z.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,o.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeout)(q.isWin?(0,K.dfWin)():(0,J.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeout)(q.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,X.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,I.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,B.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,$.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,$.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,$.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),a=i(7162),o=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),a=i(91464),o=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),a=i(39784),o=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),a=i(88491),o=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),a=i(75556),o=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),a=i(75556),o=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*o.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.round(e/o.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,a.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),a=i(88491),o=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},95748:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(97742)),s=i(87748),a=i(7127),o=i(12374),l=i(33148),u=i(25516),c=i(38307),d=i(2126),h=i(3142),f=i(29993),m=i(51081),p=i(29663),g=i(43414),y=i(46573),v=i(28437);!async function(){r.default.argv.includes("--help")&&(console.log((0,m.joinLines)(...(0,h.cliWrap)(`This is PhotoStructure's background worker, and is for internal use only.\n${f.DescriptionFooter}`))),r.default.exit(0)),(0,u.setServiceName)(a.ServiceNames.worker),(0,l.setShortProcessNames)(g.Settings.shortProcessNames.valueOrDefault),(0,l.setProcessTitle)(),r.default.argv.includes("--volumes")&&(console.log((0,s.stringify)(await(0,y.volumes)())),r.default.exit(0)),(0,o.addDefaultJsonRevivers)(),(0,d.exitOnStdStream)(),p.onProgressEvt.setShim((async e=>{(0,c.stdoutWrite)(e,void 0)})),(0,v.handleWorkRequests)()}()},48011:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=void 0;const n=i(75556),r=i(61570),s=i(84253),a=i(75288),o=i(59873),l=i(72461),u=i(35254),c=i(19371),d=i(31216),h=i(45766);t.WorkerFunctions={assetFileMetadata_:a.assetFileMetadata_,buildAssetPreviews_:c.buildAssetPreviews_,imageHash_:l.imageHash_,ping:h.ping,prepFileForBrowser:u.prepFileForBrowser,whyInvalidFile:d.whyInvalidFile,shimmedFileSha_:o.shimmedFileSha_},t.WorkRequestMethods=(0,s.strEnum)(...(0,r.keys)(t.WorkerFunctions)),t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,n.isNumber)(e.id)}},28437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequests=t.handleWorkRequest=void 0;const r=n(i(97742)),s=i(4866),a=i(7162),o=i(38307),l=i(94329),u=i(39938),c=i(16475),d=i(87748),h=i(2934),f=i(82798),m=i(2126),p=i(24905),g=i(17875),y=i(79141),v=i(48011),w=(0,s.lazy)((()=>(0,a.mkLogger)("worker.Worker")));async function S(e){const t=v.WorkerFunctions[e?.method];if(null==t)throw new Error("invalid method "+(0,d.stringify)(e?.method));return t(e.args[0])}async function b(e){if(e=(0,f.toS)(e),(0,u.blank)(e))return;if(e.trim()===p.ChildServiceExitCommand)return(0,m.exit)({reason:e+" from stdin",status:0});const t=(0,h.parseJSON)(e);if(w().debug("onData",{request:t}),(0,v.isWorkRequest)(t))try{const e=await S(t);(0,o.stdoutWrite)({id:t.id,response:e},!0)}catch(e){const i=(0,c.errorToJson)(e);w().warn("failed to process request",{request:t,error:i}),(0,o.stdoutWrite)({id:t.id,error:i},!1)}else w().warn("not a work request",{request:t,line:e}),(0,o.stdoutWrite)({id:t?.id,request:t,error:"invalid work request"},!0)}t.handleWorkRequest=S,t.handleWorkRequests=function(){!0===r.default.stdin?.readable?(function(){for(const e of["SIGINT","SIGTERM"])r.default.on(e,(e=>(0,m.exit)({reason:e,status:0})))}(),function(){for(const e of["uncaughtException","uncaughtException","disconnect"])r.default.on(e,(e=>{const t=new y.WrappedError("uncaughtException",{cause:e});return(0,g.onError)(t)?(0,m.exit)({error:t,status:(0,c.errorErrno)(t)??1}):void 0}))}(),r.default.stdin.pipe(new l.LineReader).on("data",b),w().info("Child process mode: listening on stdin...")):(0,m.exit)({reason:"process.stdin is not readable",status:13})}},45766:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=n(i(97742)),s=i(43947),a=i(75556),o=i(19658),l=i(13378),u=i(2126),c=i(79141),d=i(32940);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,s.delay)(e.delay),o.isTest&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),a=i(87748),o=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),a=i(87748),o=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},13783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const n=i(88012),r=i(11944),s=i(39938),a=i(88491),o=i(9381),l=i(97042),u=i(75556),c=i(82798),d=i(82669),h=i(96518),f=i(39607);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const n=(0,c.toS)(e.v);return(0,s.blank)(n)||"1"===n||(i??(i=new URLSearchParams)).append("v",n),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,n.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,n.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,n.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:s,af:l}){if(null==(0,n.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const S=s&&(0,f.isSafari)((0,h.ua)());S?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const b=r.map((n=>m(y({assetId:e,params:t,reducer:i,width:n}),n)));return null!=l&&b.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(S?"data-":"")+"srcSet"]=b.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,n.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:n="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===n?80:"m"===n?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),a=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},36535:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(17954),o=i(82798);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,n.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),a=i(66776),o=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),a=i(61570);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},57743:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(75556),r=i(33714),s=i(17078);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}ร—${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function a(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=a;const o=[s,a],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of o){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){o.push(e)},t.unshiftObjComparator=function(e){o.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),a=i(75556),o=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},85643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),a=i(75556),o=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},77125:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const n=i(39938),r=i(38625),s=i(61570),a=i(61715),o=i(84253);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,n.blank)(e.id)&&!(0,n.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,n.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["โŒš Requesting health check results..."]}]:[]})))}},9381:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const n=i(84253);t.ReducerNames=(0,n.strEnum)("fit","sq")},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),a=i(11353);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),a=i(87748),o=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),a=i(90957),o=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function M(e,t){return l(e)?t(e):void 0}function _(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function x(e,t){if(null==e)return 0;const i=Math.pow(10,t);return _(e*i)/i}function E(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=M,t.map2Numeric=function(e,t,i){return M(e,(e=>M(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=_,t.toFixed=function(e,t){try{return M(e,(e=>_(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=x,t.toPrecisionMaybe=function(e,t){return h(e,(e=>x(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-_(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?_(e/n)*n:_(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,S(t)?_(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),a=i(47025),o=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},71756:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},17954:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let n=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,n=n.slice(0,r.index)+i(r)+n.slice(r.index+r[0].length);return n}},33714:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(75556);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},61715:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const n=i(84253);t.RunStates=(0,n.strEnum)("loading","welcome","ready","failed")},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),a=i(1429),o=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),a=i(21669);async function o(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,a)=>{let o=!0;const l=setTimeout((()=>{o&&(o=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;o&&(o=!1,s(t))}catch(e){o&&(o=!1,a(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await o(e,i,r);if(s===t.Timeout)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=o,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:o(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new a.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const a=await o(e,i,r);return a===t.Timeout?(0,s.tot)(n):a}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),a=i(71756),o=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=h[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},23022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},96518:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const n=i(11448),r=i(82798);t.ua=(0,n.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},39607:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},88012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const n=i(66776),r=i(75556);function s(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,n.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),a=i(82798);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},99957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),i(95748)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},9160:e=>{e.exports=require("@photostructure/tz-lookup")},5712:e=>{e.exports=require("batch-cluster")},71239:e=>{e.exports=require("events")},889:e=>{e.exports=require("exiftool-vendored")},25861:e=>{e.exports=require("fast-xml-parser")},53221:e=>{e.exports=require("file-type")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},89965:e=>{e.exports=require("ml-kmeans")},78932:e=>{e.exports=require("picomatch")},55543:e=>{e.exports=require("plist")},39369:e=>{e.exports=require("process")},46850:e=>{e.exports=require("punycode")},10912:e=>{e.exports=require("semver")},57441:e=>{e.exports=require("sharp")},41313:e=>{e.exports=require("trash")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},87503:e=>{e.exports=require("node:net")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=99957);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/package.json b/package.json index 6f1e377..35fa7e0 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "photostructure", "productName": "PhotoStructure", "author": "PhotoStructure, Inc. ", - "version": "2023.12.0-alpha.5", + "version": "2023.12.0-alpha.6", "license": "SEE LICENSE IN LICENSE.md", "description": "PhotoStructure for Servers", "homepage": "https://photostructure.com/server/photostructure-for-node/", diff --git a/photostructure b/photostructure index 85c2584..b292f17 100755 --- a/photostructure +++ b/photostructure @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function C(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await C(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),_=i(51053),M=i(43414),E=i(53719);class x extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=x,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(_.isWin?3:1)*o.minuteMs,maxTasksPerProcess:M.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:M.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:M.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?M():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function M(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),_=i(4691),M=i(46852),E=i(46027),x=i(4586),T=i(17875),C=i(98462),D=i(25015),k=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,D.isJsonExt)(t)&&(0,k.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,k.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,M.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,x.configDir)(),(e=>new j(C.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:R)).filter((e=>x(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function C(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=x,t.ps=async function(){const e=await(_.isWin?async function(){if(M.PowerShell.instance().ended)return A();const e=await M.PowerShell.instance().executeJsonToA([D,k].join(" "));return null==e?A():C(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(x),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const D="Get-Process",k="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return A(e);const t=[D,"-Id",O(e),"-ErrorAction SilentlyContinue",k].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>C(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function C(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=C,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const M=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.5",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",5],t.release="2023.12.0-alpha.5+20231217214814",t.gitSha="9cdc7207350c3cab07b8b5255f2134dc354de3a3",t.gitDate=new Date(1702878494e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),_=i(75556),M=i(61570),E=i(26588),x=i(46234),T=i(21669),C=i(7162),D=i(49379),k=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,C.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,_.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,C.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function _(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=_,t.rejected=async function(e){return!await _(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),n=t();return M(e,Date.now()-i),n},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>_(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const _=["HOME","LANG","USER"],M=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?_:M),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function x(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=x,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:C({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function C({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...x(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=C},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),_=i(34996),M=i(46027),E=i(49379),x=i(79141),T=i(83837),C=i(95976),D=i(10347),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,M.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,D.spawnOptions)(n);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new _.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),k().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const M=y.join("");(0,l.notBlank)(M)&&v.push(new Error(M)),!n&&(0,a.isNotEmpty)(v)&&k().warn(m+" resulted in errors:",v);const C=i.isIgnorableError??E.isIgnorableError,D=v.filter((e=>!0!==C(e)));if(D.length>0)throw 1===D.length?D[0]:new x.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:M}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,D.spawnOptions)(n);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),_=i(53525),M=i(17875),E=i(79141),x=i(45512),T=i(7162),C=i(75405),D=i(43414),k=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,M.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,C.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),_=i(95699),M=i(58676),E=i(51510),x=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function C(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function D(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...C()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...C()),i}t.tmpCacheDirs=C,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:C(),desc:"tmp"})},t.cacheDirs=D,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:D(),desc:"cache"})));const k=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{k();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await M(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),_=i(59694),M=i(38625),E=i(88491),x=i(43383),T=i(24603),C=i(16475),D=i(1429),k=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),j=i(70283),B=i(55568),V=i(14889),z=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),J=i(91641),$=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,z.StartTs):n}function Se(e){const t=(0,_.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,k.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,M.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,k.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,D.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,D.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,_.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,k.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,x.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,C.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),_=i(11944),M=i(92585),E=i(39938),x=i(88491),T=i(24603),C=i(1429),D=i(87748),k=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),j=i(13779),B=i(34996),V=i(46852),z=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),J=i(7162),$=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,C.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,z.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,z.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,k.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*x.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new M(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),_=b(i(44470)),M=i(92332),E=i(11944),x=i(37609),T=i(88491),C=i(24603),D=i(19067),k=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),j=i(91641),B=i(95557),V=i(4691),z=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,z.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,C.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,k.map)(w(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),_=i(28807),M=i(91641),E=i(17354),x=i(79015),T=i(3955),C=i(8177),D=i(43414),k=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends _.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,C.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,C.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends _.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:M.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,x.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),D.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:D.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,k.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const _=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function M(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&_().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return x(e,i,t);const n=await Promise.race([E(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function x(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&x(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,M)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=M},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function _(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return D(e).some(_)},t.isNotHiddenPosixPath=function(e){return D(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function x(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function C(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function D(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function k(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return C(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return C(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return C(w.toNativePath_,e,t)},t.toPathnames=D,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&D(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:D(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=D(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return D(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return D(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=k,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(k(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),_=i(19067),M=i(66776),E=i(75556),x=i(61570),T=i(20636),C=i(49049),D=i(17078),k=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),j=i(69317),B=i(14195),V=i(53525),z=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),J=i(43414),$=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===C.PS_LIBRARY_SCHEME?1:t.scheme===C.PS_LOCAL_FILE_SCHEME?2:t.scheme===C.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const _=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=x(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):x(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function _(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=_,t.statEql=function(e,t){return null==_(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),_=i(51053),M=i(43414),E=i(53719),x="{ready}",T=" | ConvertTo-Json -Compress";function C(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=C,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+C(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,r.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),_=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],_.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],_.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],_.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),_=i(27387),M=i(29393),E=i(94794),x=i(7560),T=i(45005),C=i(20902),D=i(6565),k=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),j=i(98788),B=i(61659),V=i(40185),z=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),J=i(1440),$=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:D.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:k.CropStrategies.attention,strEnum:k.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:z.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,C.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?M:_;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:_(a,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=E;const C=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(C)?e.replace(C,(e=>T(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),_=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(M)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function C(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(C)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),_=i(7903),M=i(55412),E=i(62255),x=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await C(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,x.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+x.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const C=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),_=i(95725),M=i(76531),E=i(51053),x=i(43414),T=i(39206),C=i(36736),D=i(62255),k=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{x.Settings.libraryDir.watchLater(L),x.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,D.maybeWatchProcMounts)(),await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=x.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||x.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,_.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),L()})),x.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=M,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=x,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(_)?new h.FsWatcher({target:_,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+_),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),_=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function M(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await x(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>_.clear())),w.mountpoints.watchLater((()=>_.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(M(e))return;if((0,o.isFalse)(e.ok))return;const t=await _().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=M,t.toVolumeUUID=E,t.readUuidFile_=x,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),_=i(55568),M=i(91710),E=i(14889),x=i(91464),T=i(46852),C=i(37121),D=i(1629),k=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),j=i(3955),B=i(98250),V=i(95725),z=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),J=i(47044),$=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,x.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,_.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,x.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,x.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,x.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,_.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,x.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function _(e,t){return l(e)?t(e):void 0}function M(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return M(e*i)/i}function x(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=_,t.map2Numeric=function(e,t,i){return _(e,(e=>_(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=M,t.toFixed=function(e,t){try{return _(e,(e=>M(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-M(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?M(e/n)*n:M(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=x,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return x(0,100,S(t)?M(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},87978:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(7304),s=n(i(87561)),o=n(i(49411)),a=i(97742),l=i(42041),u=i(79682),c=i(38507);function d(e){for(const t of["bin",__dirname]){const i=o.default.join(t,e);if(s.default.existsSync(i))return i}return console.error("failed to find command "+e),e}r.program.version(l.version),r.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,c.verifyUidGid)(),(0,u.addFooter)(r.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:d("main.js")}).command("info",u.CliDesc.info,{executableFile:d("info.js")}).command("list",u.CliDesc.list,{executableFile:d("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:d("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:d("logtail.js")}).command("web",u.CliDesc.web,{executableFile:d("web.js")}).command("sync",u.CliDesc.sync,{executableFile:d("sync.js")}).parse(a.argv)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(87978);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={9678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(4866),r=i(19658),s=i(42041);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+(r.isProd?"":`-${r.nodeEnv}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},13779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverseG=t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=void 0;const n=i(11944),r=i(14439),s=i(59694),o=i(39938),a=i(24603),l=i(87748),u=i(66776),c=i(75556),d=i(61570),h=i(8199),f=i(39784),m=i(47003);var p=i(11944);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=Math.max(...e.map((e=>e?.length??0)));return(0,c.times)(t,(t=>e.map((e=>e?.[t]))))}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function C(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await C(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},13056:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const r=n(i(97742)),s=i(4866),o=i(88491),a=i(66776),l=i(75556),u=i(21669),c=i(82798),d=i(7162),h=i(92661),f=i(4437),m=i(14889),p=i(91641),g=i(95557),y=i(4691),v=i(49273),w=i(10408),S=i(53525),b=i(49379),P=i(17875),_=i(51053),M=i(43414),E=i(53719);class x extends g.EndableWrapper{constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>this.t.end()),i,"worker"===e?(0,E.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const n=t;n.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,h.addPid)({pid:i.pid,ppid:r.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new u.TimeoutError)})),n.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),n.on("taskError",((e,t)=>{null!=(0,w.errorToS)(e).match(/timeout/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,a.map)(t,(e=>e.command)),e)})),n.on("fatalError",(e=>{this.onError("on(fatalError)"+S.FatalErrorFlag,e)})),n.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),n.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),n.on("childEnd",(e=>{(0,l.gt0)(e?.pid)&&(this.logger.info("on(childExit)",e.pid),h.Pids.instance()?.onKill(e.pid))}))}onError(e,t){this.t.ended||(0,y.ending)()||!1!==(0,b.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable): "+e,t):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=x,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(_.isWin?3:1)*o.minuteMs,maxTasksPerProcess:M.Settings.maxTasksPerProcess.valueOrDefault,spawnTimeoutMillis:(0,E.commandTimeoutMs)(),minDelayBetweenSpawnMillis:M.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:M.Settings.streamFlushMs.valueOrDefault,cleanupChildProcs:!1,logger:(0,s.lazy)((()=>(0,d.mkLogger)(t)))}}},24945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const n=i(75556);class r{constructor(e){if(this.maxLength=e,this._length=0,this._firstIndex=0,e>1e3)throw new Error("BoundedList.maxLength of "+e);this.store=new Array(...(0,n.times)(e,(()=>null)))}mapIndex(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this._length),e<0||e>=this._length?void 0:t((e+this._firstIndex+this.maxLength)%this.maxLength)}at(e){return this.mapIndex(e,(e=>this.store[e]))}get last(){return this.at(-1)}set(e,t){return this.mapIndex(e,(e=>this.store[e]=t))}get length(){return this._length}set length(e){this._length=(0,n.clamp)(0,this._length,e)}clear(){this.length=0}[Symbol.iterator](){const e=this;return function*(){for(let t=0;te.store[t]))}()}push(...e){for(const t of e.slice(-this.maxLength))this._length{this.store[e]=t}));return this._length}pop(){return this.mapIndex(this._length-1,(e=>(this._length--,this.store[e])))}unshift(...e){for(const t of e.reverse())this._length{this.store[e]=t,this._firstIndex=e}));return this._length}shift(){return this.mapIndex(0,(e=>(this._firstIndex++,this._length--,this.store[e])))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{this.mapIndex(this._length-1-e,(e=>{const i=this.store[e];this.store[e]=this.store[t],this.store[t]=i}))}));return this}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=r},83486:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(82798),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=o},36218:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(97461);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},32843:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(11944),a=i(89253),l=s(i(61570)),u=i(39784),c=i(2073);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>r){const e=this.getFirst(s);null!=e&&(n=e,r=o)}}return n}get(e){return this.lookup(e)?.value}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},26302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.setColorEnabled=void 0;const n=i(21941);let r=!(0,n.noColor)();function s(e,t){return i=>r?`[${e}m${i}[${t}m`:i}t.setColorEnabled=function(e){r=e??!(0,n.noColor)()},t.reset=s(0,0),t.bold=s(1,22),t.dim=s(2,22),t.italic=s(3,23),t.underline=s(4,24),t.overline=s(53,55),t.inverse=s(7,27),t.hidden=s(8,28),t.strikethrough=s(9,29),t.black=s(30,39),t.red=s(31,39),t.green=s(32,39),t.yellow=s(33,39),t.blue=s(34,39),t.magenta=s(35,39),t.cyan=s(36,39),t.lightGrey=s(37,39),t.darkGrey=s(90,39),t.redBright=s(91,39),t.greenBright=s(92,39),t.yellowBright=s(93,39),t.blueBright=s(94,39),t.magentaBright=s(95,39),t.cyanBright=s(96,39),t.white=s(97,39),t.bgBlack=s(40,49),t.bgRed=s(41,49),t.bgGreen=s(42,49),t.bgYellow=s(43,49),t.bgBlue=s(44,49),t.bgMagenta=s(45,49),t.bgCyan=s(46,49),t.bgLightGrey=s(47,49),t.bgDarkGrey=s(100,49),t.bgRedBright=s(101,49),t.bgGreenBright=s(102,49),t.bgYellowBright=s(103,49),t.bgBlueBright=s(104,49),t.bgMagentaBright=s(105,49),t.bgCyanBright=s(106,49),t.bgWhite=s(107,49)},94383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(59694),r=i(75556),s=i(61570),o=i(82798),a=i(60346),l=i(6667);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},71215:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern=["key(?!word)","aws_","npm_","pass","private","secret","token"].join("|")},70403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(66776);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},10926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(39653),r=i(4866),s=i(98250);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},39653:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(4866),r=i(40786),s=i(3955);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},3396:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},51498:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(75556),a=i(82798),l=i(8177),u=i(46027);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},31737:function(e,t,i){var n,r,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(75556),d=i(21669),h=i(82798),f=i(51498),m=i(34996);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(o=l(this,n,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(a=l(this,n,"f"),++a),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(n=l(this,a,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},32614:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},82128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(61570),l=i(7162),u=i(1058),c=i(91464),d=i(51081);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,a=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(a,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},25452:function(e,t){var i,n=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},r=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Halt=void 0,t.Halt=class{constructor(){i.set(this,!1)}get halted(){return n(this,i,"f")}halt(){r(this,i,!0,"f")}},i=new WeakMap},24588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},79378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(93977),r=i(87748);var s=i(87748);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},4866:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(47261),a=i(11944),l=i(24603),u=i(75556),c=i(11353),d=i(3396);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(7162),l=i(91464),u=i(20681),c=i(46852),d=i(69317),h=i(29405),f=i(28649),m=i(51053),p=i(71663),g=i(53719);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?M():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function M(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},7162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(4866),r=i(74269),s=i(78109);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const o=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},48783:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(11944),r=i(66776),s=i(39784),o=i(13779);function a(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},81765:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(87748),r=i(51498);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},21941:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noColor=void 0;const n=i(38625);t.noColor=function(){return(0,n.toBoolean)(process.env.PS_LOG_COLOR)??(0,n.toBoolean)(process.env.NO_COLOR)??["dumb","unknown"].includes(process.env.TERM)}},19658:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=t._nodeEnv=void 0;const r=n(i(97742)),s=i(38625),o=i(82798),a=i(94845),l=/mocha\.js$|\.spec\.js$/;function u(){switch((0,o.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":case"testing":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return!(0,a.isPacked)()&&r.default.argv.some((e=>null!=l.exec(e)))?"test":"production"}}t._nodeEnv=u,t.nodeEnv=r.default.env.NODE_ENV=u(),t.isDev="development"===t.nodeEnv,t.isTest="test"===t.nodeEnv,t.isProd="production"===t.nodeEnv,t.isSingleSpecTests=function(){return t.isTest&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},70283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.mapGt0Or=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(66776),a=i(75556),l=i(65113),u=i(82798),c=i(70208);var d=i(75556);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}function f(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=f,t.map2Gt0=function(e,t,i){const n=(0,a.toInt)(e),r=(0,a.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0},t.mapGt0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)};const m=/[+-]?[\d,.]+/;function p(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,o.map)(m.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(p(e))}function y(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function v(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return p(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:(0,o.orElse)(this.store[e*this.columns+t],(()=>0))}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(y(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(y(e,t),(([e,t])=>v(e,t)))},t.hammRatioBinaryString=v,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.eqlSubset=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(11944),r=i(88491),s=i(24603),o=i(1429),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(50530),h=i(13779),f=i(91464);function m(e,t){try{return e()}catch(e){return t?.((0,d.toErr)(e))}}function p(e){return(0,u.keys)(e).filter((t=>(0,c.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const i={};for(const[n,r]of(0,u.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach((e=>m((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of p(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,u.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,u.keys)(e))if(n[s]=t(s,e[s]),r++,(0,l.gt)(r,i))break;return n},t.eqlSubset=function(e,t){return null!=e&&(0,u.keys)(e).every((i=>(0,s.eql)(e[i],t[i])))},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):g(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,o.flatten)(e.map(u.keys))))t[i]=e.map((e=>e?.[i]));return t}},75405:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(5712),r=i(39784),s=i(21142);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},92661:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProcCleaner=t.addPid=t.Pids=t.killPid=void 0;const r=i(5712),s=n(i(17718)),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(88491),d=i(66776),h=i(75556),f=i(98510),m=i(39784),p=i(82798),g=i(51498),y=i(7162),v=i(2023),w=i(18),S=i(99869),b=i(91641),P=i(95557),_=i(4691),M=i(46852),E=i(46027),x=i(4586),T=i(17875),C=i(98462),D=i(25015),k=i(3955),O=i(51053),I=i(71663),F=(0,a.lazy)((()=>(0,y.mkLogger)("proc.Pids"))),L=10*c.secondMs;function A(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,d.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,h.gt0)(i)&&(0,h.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*c.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,D.isJsonExt)(t)&&(0,k.isHiddenBasename)(t.base)&&(0,h.lt)(t.mtimeMs(),e)));for(const e of(0,m.toA)(t))F().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,S.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:c.minuteMs,f:async(e={})=>{await this.vacuumOldWip();const t=e.everything??!1,i=e.force??O.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,l.isEmpty)(r))return F().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,w.pidInfos)(r);if(null!=a){for(const r of n){const n=await r.readJson();if(null==n){F().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,h.gt0)(l)){F().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!A(n,u)){F().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,h.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,h.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,h.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(F().info("killOldProcs(): killing",{reason:d,json:n}),o.push(R(l,i,!1)),s.push({...n,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,T.onError)("Pids.killOldProcs(): failed to get process information")}})}async addPid(e,t,i=!1){if(null==e)throw new Error("undefined info");const n=e.pid;if(!(0,h.gt0)(n))throw new Error("undefined pid");const s=e.ppid+":"+e.pid;return(0,r.pidExists)(n)?(i&&this.recentPids.delete(s),this.recentPids.getOrSet(s,(async()=>{const i=this.pidsDir.join(e.pid+".json"),n=(0,f.opt)((0,v.Try)((()=>(0,k.parseNativePath)(e.cmd).base))).filter(u.notBlank).getOrElse((()=>e.cmd)),r=t.getTime(),s={...e,cmd:n,startTime:r};return await i.writeJson_(s),F().debug("addPid() wrote "+i,s),i}))):(this.recentPids.delete(s),void F().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,h.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==o.default.pid}))}async pids(e=this.pidfiles()){return(0,l.compact)((0,m.toA)(await e).map((e=>(0,h.toInt)(e.name))))}async onKill(e){const t=this.pidsDir.join(e+".json");return(0,M.thenMap)(t.clear().readJson(),(t=>this.addPid({...t,timeoutMs:1},(0,c.ago)(c.minuteMs),!0).catch((t=>{F().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}}t.Pids=j,j.instance=(0,a.lazy)((()=>(0,d.map)((0,x.configDir)(),(e=>new j(C.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return j.instance()?.addPid(e,t)},t.ProcCleaner=(0,a.lazy)((()=>{const e=[{everything:!1,force:!1,intervalMs:5*c.minuteMs},{everything:!1,force:!0,intervalMs:17*c.minuteMs}].map((e=>(0,E.setUnrefInterval)((()=>j.instance()?.killOldProcs(e)),e.intervalMs)));return new P.EndableWrapper("ProcCleaner",(()=>(e.map(clearInterval),j.instance()?.killOldProcs())),b.EndableRanks.predb)}))},86725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(70612)),s=i(84253);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e(0,g.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function T(e){const t=(0,y.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:R)).filter((e=>x(e)&&t.includes(e.pid)));return E().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}function C(e){return e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))}t.isProcEntry=x,t.ps=async function(){const e=await(_.isWin?async function(){if(M.PowerShell.instance().ended)return A();const e=await M.PowerShell.instance().executeJsonToA([D,k].join(" "));return null==e?A():C(e)}():async function(){return N(await(0,b.stdout_)("ps",["-ewwwo","pid,lstart,command"],F))}());return(0,a.sortBy)(e.filter(x),(e=>e.pid))??[]},t.pidInfo=async function(e){return(0,S.thenMap)(T([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,y.existingPids)(e),(t=>{const i=[r.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=T;const D="Get-Process",k="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return A(e);const t=[D,"-Id",O(e),"-ErrorAction SilentlyContinue",k].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>C(e)))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function A(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),r.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),n=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===r.default.pid))||n.push({pid:r.default.pid,start:new Date(v.StartTs),cmd:"node "+r.default.title}),n}function N(e){return(0,l.blank)(e)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],e).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})))}async function R(e){return N((await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result)}t.psWinWmic=A},99869:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(43947),r=i(6314),s=i(75556),o=i(34996),a=i(46027),l=i(79141);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}const v=(...r)=>{if(g()){if(!0===u)return null;const e=d?.promise;return h=r,(0,n.delay)(1).then((()=>e))}return async function(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new o.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{!async function(){f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}()}return r.promise}(...r)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),f=!1,m=0,v(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},1058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(61570),r=i(82798);function s(e){return e instanceof o?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[โ€˜โ€™']/g,"[โ€˜โ€™']").replace(/[โ€œโ€โ€žยซยปใ€ƒ"]/g,'[โ€œโ€โ€žโ€ยซยปใ€ƒ"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,n||(n=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},4437:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(88491),u=i(43947),c=i(1429),d=i(75556),h=i(44726),f=i(82798),m=i(7162),p=i(86725),g=i(31329),y=i(69317),v=i(79015),w=i(51053),S=i(71663),b=i(43414),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},55568:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.isModelDbMigrator=t.isStatsDbMigrator=t.isStatsDbService=t.StatsDbServices=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(97742)),s=i(4866),o=i(11944),a=i(7127),l=i(82798),u=i(19658),c=i(94845);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}function g(){return(u.isTest||p())&&!f()}function y(){return m()}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.StatsDbServices=[a.ServiceNames.sync],t.isStatsDbService=y,t.isStatsDbMigrator=function(){return y()||g()},t.isModelDbMigrator=function(){return m()||h()||g()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p()))},8177:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(39784);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},91710:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const n=i(7383);t.shim0=function({impl:e,name:t}){let i;const r=()=>(0,n.time)(t+(null==i?"(local)":"(remote)"),null!=i?i():e());return r.setShim=e=>{i=e},r.hasShim=()=>null!=i,r}},13378:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const n=i(87748),r=i(44726),s=i(79015);t.shim1=function({name:e,impl:t,cache:i,toKey:o=(e=>(0,r.isString)(e)?e:(0,n.stringify)(e))}){let a;const l=async i=>{const n=Date.now(),r=await(null!=a?a(i):t(i));return(0,s.ee)().emit("timing",e+(null==a?"(local)":"(remote)"),Date.now()-n),r},u=async e=>null==i?l(e):i().getOrSetAsync(o(e),(async()=>l(e)));return u.setShim=e=>{a=e},u.hasShim=()=>null!=a,u.cache=i,u.cacheDelete=e=>i?.().delete(o(e)),u}},14889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(88491);t.ShortCommandTimeoutMs=7*n.secondMs},55413:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(37609);t.SortedSet=class{constructor(e){this.valueOf=e,this.store=[]}get length(){return this.store.length}addAll(...e){return e.map((e=>this.add(e)))}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=this.store.length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),r=this.valueOf(this.store[n]);if(e===r)return{found:!0,index:n};e>r?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&this.store.splice(t.index,0,e),t}at(e){return(0,n.at)(this.store,e)}toA(){return[...this.store]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.store.length-1){const e=[...this.store];return this.store.length=0,e}return this.store.splice(0,t.index+(t.found?1:0))}splice(e,t){return this.store.splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},58623:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(97742),r=i(18991);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},38307:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(97742)),s=i(39938),o=i(87748),a=i(55568),l=i(58623),u=i(53525),c=i(49379),d=i(18991);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);n.write(r+"\n"),(0,a.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},91464:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(66776),a=i(75556),l=i(65113),u=i(8199),c=i(44726),d=i(39784),h=i(82798),f=i(13779),m=i(1058),p=i(53525);var g=i(83511);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(44726);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(1604);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,a.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" โ€ฆ(+"+r+" chars)โ€ฆ"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[โ€˜โ€™]/g,"'"],[/[โ€œโ€โ€žยซยปใ€ƒ]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['โ€˜โ€™].*['โ€˜โ€™]$/,T=/^["โ€œโ€โ€žยซยปใ€ƒ].*["โ€œโ€โ€žยซยปใ€ƒ]$/;function C(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=C,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},63774:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(82798);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},29731:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(6005)),s=i(24588),o=i(6231);function a(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,n=224){return i.encodeBuffer(a(e,n)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,n=224){return l(e,t,i,n)}},97461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(82798);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},2073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(75556),a=i(65113),l=i(44726),u=i(82798),c=i(6231),d=i(70283),h=i(2023),f=i(8177),m=i(91464);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,o),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,o.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const M=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,o.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(n),(e=>e),256),a=(0,o.clamp)(-256,256,r-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},47003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(87748),r=i(2023);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},3917:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(59694),m=i(88491),p=i(46027);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},31329:function(e,t,i){var n,r,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(46027);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,n,"m",r).call(this,e,t)}},16417:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},37086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const n=i(4866),r=i(59694),s=i(39938),o=i(82798),a=i(19658),l=i(6231);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,n.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,o.toS)(e).replace(/(?<=\S)-.*/,"");return(0,s.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,o.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,r.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!a.isTest)throw new Error("unsupported");t.uidSuffix.unset(),u=0}},24586:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(38625),c=i(75556),d=i(7162),h=i(14889),f=i(69317),m=i(20902),p=i(51053),g=i(71663),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},42041:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2023.12.0-alpha.6",t.versionMajor=2023,t.versionMinor=12,t.versionPatch=0,t.versionPrerelease=["alpha",6],t.release="2023.12.0-alpha.6+20231217225159",t.gitSha="0ed4df2dc131e503da6a162b731b022c60a58207",t.gitDate=new Date(1702882319e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},3867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(88491),r=i(66776),s=i(75556),o=i(98510),a=i(70283),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},78342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},12308:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(92332)),s=i(75556);t.debounce=function(e,t){let i,n=[];const o=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return o.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},34996:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(92332)),w=y(i(47261)),S=i(43383),b=i(16475),P=i(66776),_=i(75556),M=i(61570),E=i(26588),x=i(46234),T=i(21669),C=i(7162),D=i(49379),k=i(49273),O="TIMEOUT",I=(0,S.defer)((()=>(0,C.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e];for((0,_.gt0)(t)&&i.push(new r(O).setTimeout(t));i.some((e=>e.name!==O));){const e=i.findIndex((e=>!e.isPending));if(e>=0){const n=i[e];if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map((e=>e.name))});i.splice(e,1),yield n}else try{await Promise.race(i)}catch{}}}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,C.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}setTimeout(e,t=!0){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f")),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),t&&p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,r=F,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},36079:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(89253),a=i(20636),l=i(7162),u=i(19658),c=i(70283),d=i(42648),h=i(91641),f=i(4691),m=i(46027),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=u.isTest&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?100:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,a.thenOrTimeoutError)(i.end(),n,!1)}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:u.isTest,isSingleSpecTests:(0,u.isSingleSpecTests)()}),u.isTest||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},28807:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(92332),h=i(66776),f=i(75556),m=i(61570),p=i(91641),g=i(95557),y=i(4691);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",o).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},91641:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(84253);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail")},95557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(4866),l=i(6314),u=i(7162),c=i(36079),d=i(91641),h=i(46852);t.EndableWrapper=class{constructor(e,t,i=d.EndableRanks.first,o){this.endTimeoutMs=o,n.set(this,void 0),this.onEnds=[],r.set(this,(0,a.lazy)((()=>new l.Latch))),this.end=(0,a.lazy)((async()=>{await(0,h.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,c.addEndable)(i,this)}setName(e){o(this,n,e,"f"),this.logger=(0,u.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}},n=new WeakMap,r=new WeakMap},4691:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(19658);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=n.isTest?e:e||r}},2126:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(97742)),s=i(39938),o=i(43383),a=i(26302),l=i(7162),u=i(38307),c=i(79141),d=i(9483),h=i(43414),f=i(36079),m=i(4691),p=i(7383),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},20681:function(e,t,i){var n,r,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(24603),m=i(75556),p=i(50530),g=i(3396),y=i(34996);t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new v(e,t,i,n)};class v extends g.ExtensibleFunction{constructor(e,t,i,u){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=u,r.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,void 0),l.set(this,[])}_call(){return this.isStale()?d(this,n,"m",c).call(this,this.later()):d(this,a,"f")}unset(){h(this,s,0,"f"),h(this,r,void 0,"f"),h(this,o,void 0,"f"),h(this,a,void 0,"f")}set(e){return d(this,n,"m",c).call(this,y.Deferred.resolve(e))}refresh(){return d(this,n,"m",c).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){d(this,l,"f").push(e)}prior(){return this.isStale()?void 0:d(this,a,"f")}lastValue(){return d(this,a,"f")?.value??d(this,o,"f")}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return d(this,s,"f")}isStale(){return null==d(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-d(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==d(this,r,"f")?void 0:Date.now()-d(this,r,"f")}elapsedMs(){return d(this,a,"f")?.settledMs??d(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,n=new WeakSet,u=async function(e,t){var i;const n=d(this,a,"f")?.id;try{const i=await t;if(d(this,a,"f")?.id===n&&h(this,o,i,"f"),d(this,a,"f")?.id===n&&!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of d(this,l,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(null!=t)for(const e of d(this,l,"f"))e.onError(t)}finally{h(this,s,(i=d(this,s,"f"),++i),"f")}},c=function(e){h(this,r,Date.now(),"f");const t=d(this,a,"f");return h(this,a,e instanceof y.Deferred?e:new y.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&d(this,a,"f").setTimeout(this.timeoutMs),d(this,n,"m",u).call(this,t,d(this,a,"f")),d(this,a,"f")}},97503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(87748),r=i(31737);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},17354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const n=i(29106);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){let r,s=!1,o=!1;const a=()=>s?(o=!0,!0===i?void 0:r):(s=!0,r=(0,n.postrun)({fn:e,postrun:()=>{s=!1,!0===t&&o&&(o=!1,setImmediate(a))}}));return a.isRunning=()=>s,a.prior=()=>r,a.force=async()=>(await r,a()),a}},29106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},46852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(11944),r=i(59694),s=i(38625),o=i(88491),a=i(43947),l=i(66776),u=i(75556),c=i(26588),d=i(20636),h=i(90957),f=i(47025),m=i(39784),p=i(50530),g=i(13779),y=i(7162),v=i(2023),w=i(59387),S=i(70259);var b=i(26588);async function P(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function _(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const o of(0,n.compact)(await t))try{const e=await((0,u.gt0)(r)?(0,d.thenOrTimeoutError)(i(o),r):i(o));null!=e&&s.push([e,o])}catch(t){(0,y.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,n.compact)(await e);if((0,n.isEmpty)(a))return[];if((r=Math.round(r??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const l=o??(a.length<=r?S.PermissivePromises:new S.Promises(i,(()=>r))),c=(0,u.gt0)(s)?e=>(0,d.thenOrTimeoutError)(t(e),s):t,h=await l.enqueueAll(i,a.map((e=>async()=>{try{return[await c(e),e]}catch(t){return void(0,y.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=P,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,g.batches)((0,m.toA)(await e),t)){const e=await P(r);n.push(...await P(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,c.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=_,t.rejected=async function(e){return!await _(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,m.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,m.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,m.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await E({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,n)}catch(e){i((0,p.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,f.isFunction)(e)?e():e)}catch(e){r=(0,p.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const o=await i(r,s);return null==o?n():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return(0,l.orElse)(await e,t)},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=v.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,p.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await E({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},7383:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(21040),l=i(75556),u=i(61570),c=i(90957),d=i(50530),h=i(94383),f=i(70403),m=i(7162),p=i(19658),g=i(79015),y=i(60346),v=i(91641),w=i(95557),S=i(46027);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.ee)().on("timing",((t,i)=>e.push(t,i))),p.isTest&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),n=t();return M(e,Date.now()-i),n},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>_(e,t)),i)}},70259:function(e,t,i){var n,r,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(71239)),m=i(11944),p=i(66776),g=i(75556),y=i(90957),v=i(82798),w=i(24945),S=i(60346),b=i(59387),P=i(34996);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum(),d(this,o,"f")}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t){return this.enqueue({name:e,l:t,serialId:e})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=(0,m.compact)(d(this,o,"f").map((e=>e.serialId))),r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,r=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,a,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},37121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.timeoutStacks=void 0;const n=i(41135),r=i(43947),s=i(75556);t.timeoutStacks=[],t.thenOrTimeout=async function(e,t,i,o){if(!(0,s.gt0)(t)){const t=await(0,n.asPromise)(e);return await(o?.(t)),t}let a,l=!1,u=!1;return await Promise.race([(0,n.asPromise)(e).then((e=>u?void 0:(a=e,l=!0,e))),(0,r.delay)(t).then((()=>{l||(u=!0)}))]),l?await(o?.(a)):await(i?.()),a}},49273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},46027:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(92332);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},21142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38625),r=i(88491),s=i(43947),o=i(47025),a=i(75556),l=i(14889),u=i(49273);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},10347:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(97742)),s=i(4866),o=i(43947),a=i(61570),l=i(13779),u=i(29405),c=i(60052),d=i(20902),h=i(79015),f=i(92507),m=i(95976),p=i(7162),g=i(19658),y=i(2023),v=i(15203),w=i(51053),S=i(43414),b=(0,s.lazy)((()=>new Set((0,a.values)(S.Settings).map((e=>e.key)))));t.psenv=function(){const e=b();return(0,y.sortedKeys)((0,a.filter)((0,u.env)(),(t=>"NODE_ENV"===t||e.has(t))))};const P=(0,s.lazy)((()=>{try{return new RegExp(S.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(S.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));(0,o.later)((()=>{function e(){P.unset(),t.sanitizedEnv.unset()}(0,h.ee)().on("clearCache",e),(0,h.ee)().on("settingsChanged",e);for(const t of(0,S.allSettings)())t.watchLater(e)}));const _=["HOME","LANG","USER"],M=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],E=(0,s.lazy)((()=>{const e=(0,d.caseInsensitiveEnv)().pick(...w.isPosix?_:M),t=(0,d.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,S.pathWithDefaults)(),e}));function x(e){const t={NODE_ENV:g.nodeEnv,NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[c.PS_IS_CHILD_PROCESS]="1",t[c.PS_IS_DOCKER]=(0,v.isDocker)()?"1":"0",w.isElectron&&(t[c.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,S.persistedSettings)().filter((e=>e.hasValue())))e?i.addToEnv(t):i.addToEnvMaybe(t);return t}t.sanitizedEnv=(0,s.lazy)((()=>{const e=P();return(0,y.mapEntries)(r.default.env,((t,i)=>null==e.exec(t)?i:void 0))})),t.childProcEnvSettings=x,t.spawnOptions=function(e){const t=e??{};return{...(0,a.omit)(t,"forceCLocale"),env:C({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let T=!1;function C({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,a.compactValues)({...(0,t.sanitizedEnv)(),...E(),...i?(0,f.childProcLocale)():{},...x(n),...e??{}});for(const e of(0,S.transientSettings)())e.deleteFromEnv(r);if((0,m.isLogged)("debug")&&!T){T=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,a.entries)(r),[i,n]=(0,l.partition)(t,(([e])=>"TZ"===e||"NODE_ENV"===e||e.startsWith("LC_")||e.startsWith("PS_")||null!=(0,S.getSettingByNameOrKey)(e)));e.debug("PS env:",(0,a.fromEntries)(i)),e.debug("non PS env:",(0,a.fromEntries)(n))}return r}t.childEnv=C},69317:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(17718)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(39938),u=i(88491),c=i(87748),d=i(6314),h=i(75556),f=i(61570),m=i(44726),p=i(20636),g=i(7162),y=i(19658),v=i(2023),w=i(75405),S=i(92661),b=i(4437),P=i(14889),_=i(34996),M=i(46027),E=i(49379),x=i(79141),T=i(83837),C=i(95976),D=i(10347),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,S.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,v.Try)((()=>e.unref())),(0,y.isSingleSpecTests)())return!0;if(await(0,w.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{S.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,S.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,w.waitForPidExit)(i,5e3)}function F(e,i,n,r=0){const o=new Date,a=[];return(0,b.niceable)(i,n)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,b.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&a.push((0,M.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),r-250)),a.push((0,M.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,S.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,D.spawnOptions)(n);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,m=(0,c.stringify)({pid:u,cmd:e,args:t}),g=[],y=[],v=[],w=new _.Deferred(m);o.on("error",(e=>v.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&w.isPending&&w.resolve(e)})),(0,T.endStream)(o.stdin);const S=new d.Latch;null==o.stdout?S.resolve():(o.stdout.on("error",(e=>v.push(e))),o.stdout.on("data",(e=>g.push(e))),o.stdout.on("end",(()=>S.resolve())));const b=new d.Latch;null==o.stderr||r?b.resolve():(o.stderr?.on("error",(e=>v.push(e))),o.stderr?.on("data",(e=>y.push(e))),o.stderr?.on("end",(()=>b.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:m}),await(0,p.thenOrTimeoutError)(w.promise,i.timeoutMs),k().debug("stdoutResult_() exitCode settled...",{name:m,exitCode:w.value,stdout:S.state(),stderr:b.state()}),await(0,p.thenOrTimeoutError)(S.promise,P.ShortCommandTimeoutMs),await(0,p.thenOrTimeoutError)(b.promise,P.ShortCommandTimeoutMs);const M=y.join("");(0,l.notBlank)(M)&&v.push(new Error(M)),!n&&(0,a.isNotEmpty)(v)&&k().warn(m+" resulted in errors:",v);const C=i.isIgnorableError??E.isIgnorableError,D=v.filter((e=>!0!==C(e)));if(D.length>0)throw 1===D.length?D[0]:new x.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==w.value)throw new Error(m+": exit code "+w.value);return{result:g.join(""),pid:u,code:w.value,stderr:M}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,D.spawnOptions)(n);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},95298:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(5712),h=i(4866),f=i(11944),m=i(39938),p=i(88491),g=i(66776),y=i(75556),v=i(82798),w=i(36079),S=i(91641),b=i(4691),P=i(70259),_=i(53525),M=i(17875),E=i(79141),x=i(45512),T=i(7162),C=i(75405),D=i(43414),k=i(69317);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,r,"f")||o||(this.lastError=s,(0,M.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=O,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,null==e||u(this,n,"m",o).call(this,e)},o=async function(e){if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,C.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===this.opts.onStderr?.(e)&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},10742:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(90410)),a=i(10926),l=i(16417),u=i(14195),c=i(81666),d=i(98250);function h(e){return(0,c.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e){const t=d.PosixFile.for(e),i=t.sibling(h(t));if(i.isSelfOrDescendantOf((0,a.examples)()))return o.join("$examples",i.posixPathFrom((0,a.examples)()));const n=(0,u.originalsDir)();if(i.isSelfOrDescendantOf(n))return o.join("$library",i.posixPathFrom(n));const r=t.findAncestor((e=>e.base.startsWith(l.TestLibraryDirPrefix)));return null!=r?o.join("$library",i.posixPathFrom(r)):t.baseWithGrandparent},t.stableBasename=h},79682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addFooter=t.CliDesc=void 0;const n=i(51081),r=i(3142),s=i(29993);t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main.",sync:"PhotoStructure's directory synchronization service. Automatically started by main."},t.addFooter=function(e){return e.on("--help",(()=>{console.log((0,n.joinLines)(...(0,r.cliWrap)(s.DescriptionFooter)))}))}},3142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=void 0;const n=i(97742),r=i(75556),s=i(44726);t.cliWrap=function(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}},29993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DescriptionFooter=void 0,t.DescriptionFooter=["",`Copyright ยฉ 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""].join("\n")},38507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const n=i(4866),r=i(11944),s=i(66776),o=i(75556),a=i(24586),l=i(29405),u=i(15203);function c(e,t,i){const n=(0,o.toGt0)((0,l.env)()[t]);return null==n||i.includes(n)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${n}`}function d(){const e=(0,r.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,n.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},80294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(42748),r=i(4866),s=i(39938),o=i(88491),a=i(66776),l=i(75556),u=i(61570),c=i(8199),d=i(7162),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},42885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(39938),r=i(75556),s=i(51498),o=i(77696),a=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},77696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(42748),r=i(11944),s=i(39938),o=i(88491),a=i(75556),l=i(44726),u=i(1058),c=i(6667);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},27387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(84253);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},29393:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(84253);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},94794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(84253);t.RepairModes=(0,n.strEnum)("dump","recover")},62936:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(84253),r=i(76915);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models","stats"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},76915:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},7560:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(84253);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},1629:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(49411)),a=i(11944),l=i(39938),u=i(66776),c=i(9678),d=i(4866),h=i(70283),f=i(24586),m=i(29405),p=i(20902),g=i(17875),y=i(79141),v=i(35694),w=i(3955),S=i(15203),b=i(51053),P=i(43414),_=i(95699),M=i(58676),E=i(51510),x=i(10156),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function C(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=b.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function D(){if((0,S.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...C()]);const e=(0,a.compactBlanks)(b.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:b.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=b.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...C()),i}t.tmpCacheDirs=C,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:C(),desc:"tmp"})},t.cacheDirs=D,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:D(),desc:"cache"})));const k=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),P.Settings.cacheDir.watchLater(O)}));function O(){P.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{k();const e=P.Settings.cacheDir.valueOrDefault;try{return(0,w.mkdirpSync_)(e),(0,v.mkNoMedia_)(e),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},4586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(4866),r=i(15203),s=i(95699),o=i(58676),a=i(66297),l=i(13773),u=i(51510);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},58676:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},5739:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(63410),r=i(15203),s=i(58676);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},66297:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(49411)),s=i(11944),o=i(9678),a=i(29405),l=i(20902),u=i(51053),c=i(51510),d=i(10156);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},13773:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(39938),r=i(20902),s=i(3955);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},51510:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44470),r=i(11944),s=i(39938),o=i(63410);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},10156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(70612),r=i(49411),s=i(4866),o=i(11944),a=i(20902),l=i(63410),u=i(51053);t.homeDir=(0,s.lazy)((()=>{const e=[];u.isWin?e.push((0,a.getEnv)("USERPROFILE")):e.push((0,a.getEnv)("HOME"));for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},85943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(3955),r=i(1629),s=i(14195);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},14195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(39938),r=i(82798),s=i(3955),o=i(43414);function a(e){return(0,n.toNotBlank)((0,r.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},82341:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(11944),r=i(66776),s=i(42041),o=i(62936),a=i(53525),l=i(35694),u=i(98250),c=i(47987),d=i(49441),h=i(43414),f=i(14195),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e))}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await M(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=E},35796:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(66776),u=i(82798),c=i(9678),d=i(20902),h=i(15203),f=i(51053),m=i(98024),p=i(13060),g=i(1629),y=i(58676),v=i(51510),w=i(10156);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},18226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(29405),a=i(51053),l=i(71663),u=i(10156);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},42648:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38625),r=i(19658),s=i(94845),o=i(29405);t.getDevEnvFlag=function(e){return!r.isProd&&!(0,s.isPacked)()&&(0,n.isTrue)((0,o.env)()[e])},t.setDevEnvFlag=function(e,t){t?(0,o.env)()[e]="true":delete(0,o.env)()[e]}},45005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38625),r=i(29405);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},29405:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(87561)),s=i(49411),o=n(i(97742)),a=i(4866),l=i(11944),u=i(39938),c=i(43947),d=i(61570),h=i(83486),f=i(79015),m=i(60052),p=i(28649),g=i(20902);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)(m.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter).filter(u.notBlank)),t=(0,g.SensitiveEnvRE)(),i={...o.default.env};for(const n of e)try{const e=(0,h.debom)(r.default.readFileSync(n)),s=(0,p.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,d.entries)(s))t.test(e)||(i[e]=n)}catch(e){console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,c.later)((()=>{(0,f.ee)().on("clearCache",(()=>t.env.unset()))}))},60052:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(84253);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},1294:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(84253);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},28649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(39938),r=i(51081);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const o of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const o=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},20902:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(97742)),s=i(4866),o=i(39938),a=i(38625),l=i(43947),u=i(32843),c=i(71215),d=i(63774),h=i(29405),f=i(1294);function m(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(f.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=m,(0,l.later)((()=>{h.env.watchLater(m)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},10408:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(5712),r=i(4866),s=i(11944),o=i(39938),a=i(16475),l=i(1429),u=i(44726),c=i(22840),d=i(82798),h=i(24945),f=i(7162),m=i(91464),p=i(51081),g=i(82987),y=i(53525),v=i(49379),w=i(79141);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),n-o.length,r)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,n).join("; ")}},82987:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(11944),r=i(16475),s=i(66776),o=i(82798),a=i(91464);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},53525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(11944),r=i(59694),s=i(84253),o=i(1058);t.ErrorFlags=(0,s.strEnum)("โฐ","ยน","ยฒ","ยณ","โด","โต","โถ","โท","โธ","โน","โ‚€","โ‚","โ‚‚","โ‚ƒ"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["ยน"],t.NonRetriableErrorFlag=t.ErrorFlags["ยฒ"],t.IgnorableErrorFlag=t.ErrorFlags["ยณ"],t.PleaseSendErrorFlag=t.ErrorFlags["โด"],t.HealthCheckErrorFlag=t.ErrorFlags["โต"],t.DoNotSendErrorFlag=t.ErrorFlags["โถ"],t.RetriableErrorFlag=t.ErrorFlags["โท"],t.HealthCheckWarningFlag=t.ErrorFlags["โธ"],t.InternalErrorFlag=t.ErrorFlags["โน"],t.NoLibraryErrorFlag=t.ErrorFlags["โ‚€"],t.DbSetupErrorFlag=t.ErrorFlags["โ‚"],t.NonFatalErrorFlag=t.ErrorFlags["โ‚‚"],t.WebFatalErrorFlag=t.ErrorFlags["โ‚ƒ"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/โน|internal ?error/i},49379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(11944),r=i(38625),s=i(16475),o=i(82798),a=i(1058),l=i(10408),u=i(53525);function c(e){return(0,o.toS)(e).replace(u.ErrorFlagsRE,"").trim()}function d(e){return u.ErrorFlags.values.filter((t=>e.includes(t)))}function h(e){return(0,l.errorToS)(e).includes(u.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,n.compact)(t).join("");return c(i)+d(i).join("")},t.stripErrorFlags=c,t.extractErrorFlags=d,t.hasErrorFlag=function(e){return u.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,l.errorToS)(e).includes(u.HealthCheckErrorFlag)},t.isPleaseSendError=h;const f=/Can't write [a-z\d]+ files/i,m=(0,a.orRegExpPatterns)([u.IgnorableErrorFlag,"0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning:/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,l.errorToS)(e);return!f.test(i)&&(!!m.test(i)||void 0)};const p=/SQLITE_BUSY|database is locked/i;function g(e){return"SQLITE_BUSY"===e.code||null!=(0,l.errorToS)(e).match(p)}function y(e){return null!=(0,l.errorToS)(e).match(/database .+ not open/i)}function v(e){return null!=(0,l.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function w(e){return!!((0,r.isFalse)(e.retriable)||(0,l.errorToS)(e).includes(u.NonRetriableErrorFlag)||v(e))||void 0}t.isSqliteBusyError=g,t.isSqliteDisconnectedError=y,t.isSqliteConstraintError=v,t.isRetriableError=function(e){if(null==e)return;if(!0===w(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||g(e)||y(e))return!0;const i=(0,l.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(u.RetriableErrorFlag))||void 0},t.isNonRetriableError=w;const S=[u.DoNotSendErrorFlag,"Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(h(e))return!1;const i=(0,l.errorToS)(e).toLowerCase();return!!S.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,l.errorToS)(e);return!!t.includes(u.FatalErrorFlag)||!t.includes(u.NonFatalErrorFlag)&&u.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||u.InternalErrorRe.test((0,l.errorToS)(e)))}},17875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(39938),r=i(75556),s=i(61570),o=i(19658),a=i(55568),l=i(2126),u=i(79015),c=i(43414),d=i(10408),h=i(53525),f=i(49379),m=i(79141),p=i(18849);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||o.isTest||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},79141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(11944),r=i(39938),s=i(38625),o=i(16475),a=i(87748),l=i(61570),u=i(39784),c=i(50530),d=i(13779),h=i(91464),f=i(10408),m=i(53525),p=i(49379);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},18849:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},56958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.broadcastExit=t.broadcastResume=t.broadcastPause=t.broadcastEvent_=void 0;const n=i(4866),r=i(87489);function s(e,...t){return r.SharedState.instance()?.broadcastEvent_({name:e,args:t})}t.broadcastEvent_=s,t.broadcastPause=function(){return s("pause")},t.broadcastResume=function(){return s("resume")},t.broadcastExit=(0,n.lazy)((()=>s("exit")))},80313:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(11944),a=i(21040),l=i(66776),u=i(82798),c=i(34996),d=i(24945),h=i(19658);t.CapturingEventEmitter=class{constructor(e,t=(h.isTest?10:0)){this.target=e,this.eventsToRetain=t,this.omniListeners=[],n.set(this,new Map),r.set(this,new Map),this.priorEvents=new d.BoundedList(t)}once(e,t){return this.target.once(e,t),this}addOmniListener(e){return this.omniListeners.push(e),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new c.Deferred("watchEvent("+(0,u.toS)(e)+")")))}removeOmniListener(e){return(0,o.filterInPlace)(this.omniListeners,(t=>t!==e))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e);for(const i of this.omniListeners)i(e,...t);this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,n,"f").get(e);return null!=o&&(o.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,l.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},82166:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSharedStateDir=void 0,i(1629);const n=i(82341);i(98250),t.DefaultSharedStateDir=function(){return(0,n.libraryDataDirPosixFile)()?.join("shared-state")}},79015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=t.mkEE=void 0;const n=i(71239),r=i(4866),s=i(80313);function o(e){const t=new n.EventEmitter;return t.setMaxListeners(70),new s.CapturingEventEmitter(t,e)}t.mkEE=o,t.ee=(0,r.lazy)(o)},95856:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setIsSyncing=t.isSyncing=void 0;const n=i(79015);let r=!1;t.isSyncing=function(){return r},t.setIsSyncing=function(e){r!==e&&(r=e,(0,n.ee)().emit("syncing",e))}},2614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TaskNameToLevel=t.EventNameToLevel=t.isTaskResult=t.isStoredTask=t.isStoredEvent=t.TaskNames=t.EventNames=void 0;const n=i(39938),r=i(61570),s=i(84253),o=i(9483),a=i(37086);t.EventNames=(0,s.strEnum)(...(0,r.keys)({exit:()=>null,updateReadyToInstall:()=>null,clearCache:()=>null,clearDbCache:()=>null,clearToolCache:()=>null,error:(e,t,i)=>null,fatal:e=>null,nonFatal:e=>null,fileChanged:e=>null,invalidFile:e=>null,mountpointsChanged:()=>null,reloadLicenses:()=>null,pause:()=>null,resume:()=>null,syncing:e=>null,progress:e=>null,updateProgress:()=>null,settingsChanged:()=>null,showAbout:()=>null,taskResult:e=>null,timing:(e,t)=>null,vacuuming:e=>null,volumesChanged:()=>null})),t.TaskNames=(0,s.strEnum)(...(0,r.keys)({checkOperations:()=>null,repairAsset:e=>null,repairAssetFile:e=>null,runTagMaintenance:()=>null,syncDir:e=>null})),t.isStoredEvent=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.EventNames.includes(e.name)&&Array.isArray(e.args)},t.isStoredTask=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&t.TaskNames.includes(e.name)&&Array.isArray(e.args)},t.isTaskResult=function(e){return"object"==typeof e&&(0,a.isUID)(e.uid)&&(0,n.notBlank)(e.result)||(0,n.notBlank)(e.error)},t.EventNameToLevel=Object.freeze({exit:o.LogLevels.warn,updateReadyToInstall:o.LogLevels.warn,clearCache:o.LogLevels.trace,clearDbCache:o.LogLevels.trace,clearToolCache:o.LogLevels.trace,error:o.LogLevels.error,fatal:o.LogLevels.fatal,fileChanged:o.LogLevels.trace,invalidFile:o.LogLevels.warn,mountpointsChanged:o.LogLevels.info,nonFatal:o.LogLevels.warn,pause:o.LogLevels.info,progress:o.LogLevels.info,updateProgress:o.LogLevels.info,reloadLicenses:o.LogLevels.info,resume:o.LogLevels.info,settingsChanged:o.LogLevels.info,showAbout:o.LogLevels.info,syncing:o.LogLevels.info,taskResult:o.LogLevels.info,timing:o.LogLevels.trace,vacuuming:o.LogLevels.info,volumesChanged:o.LogLevels.info}),t.TaskNameToLevel={checkOperations:o.LogLevels.info,repairAsset:o.LogLevels.info,repairAssetFile:o.LogLevels.info,runTagMaintenance:o.LogLevels.info,syncDir:o.LogLevels.info}},87489:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.clearSharedStates=t.submitTask_=t.SharedState=t.dedupeStoredEvents=t.isFreshEvent=t.isSharedStateFileOrDir=t.EventTimeoutMs=t.isSharedStateJson=void 0;const y=i(5712),v=i(49411),w=i(97742),S=i(92332),b=i(4866),P=i(11944),_=i(59694),M=i(38625),E=i(88491),x=i(43383),T=i(24603),C=i(16475),D=i(1429),k=i(87748),O=i(21040),I=i(66776),F=i(75556),L=i(61570),A=i(20636),N=i(39784),R=i(7162),j=i(70283),B=i(55568),V=i(14889),z=i(45113),W=i(3917),U=i(31329),q=i(37086),H=i(34996),G=i(36079),J=i(91641),$=i(95557),K=i(17354),Y=i(21142),Z=i(80294),X=i(10408),Q=i(53525),ee=i(30114),te=i(25015),ie=i(19653),ne=i(95694),re=i(95741),se=i(98250),oe=i(4931),ae=i(95725),le=i(76531),ue=i(76333),ce=i(43414),de=i(67220),he=i(79015),fe=i(95856),me=i(2614),pe=i(79781),ge=(0,b.lazy)((()=>(0,R.mkLogger)("event.SharedState")));function ye(e){return(0,te.isJsonExt)(e)&&!(0,ue.isWip)(e)}function ve(e){return(0,ne.isPsLockFileOrDir)(e)||(0,te.isJsonExt)(e)||(0,ue.isWip)(e)}function we(e){const i=(0,q.tsFromUid)(e?.uid),n=(0,me.isStoredEvent)(e)&&(0,Z.isRecentMs)(i,t.EventTimeoutMs);return n&&"exit"===e.name?(0,F.gt)(i,z.StartTs):n}function Se(e){const t=(0,_.sortBy)((0,P.compact)(e).filter(we),(e=>e.uid));return(0,P.uniqByLast)(t,(e=>(0,k.stringify)({name:e.name,args:e.args})))}t.isSharedStateJson=function(e){return null!=e&&"object"==typeof e&&(0,F.isNumber)(e.pid)&&(0,M.isBoolean)(e.paused)&&Array.isArray(e.events)&&Array.isArray(e.tasks)},t.EventTimeoutMs=E.minuteMs,t.isSharedStateFileOrDir=ve,t.isFreshEvent=we,t.dedupeStoredEvents=Se;class be extends $.EndableWrapper{constructor(e,i=String(w.pid),r=(0,he.ee)(),l=pe.taskProcessors){super("event.SharedState("+e+")#"+i,(()=>p(this,n,"m",d).call(this)),J.EndableRanks.first,ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),n.add(this),this.dir=e,this.id=i,this.eventEmitter=r,this.processors=l,s.set(this,void 0),o.set(this,new W.TTLMap(t.EventTimeoutMs)),this.handledEventUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),this.handledTaskUids=new U.TTLSet(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault),a.set(this,new W.TTLMap(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)),this.setup=(0,b.lazy)((async()=>{p(this,a,"f").on("expire",((e,t)=>{this.logger.warn("failed to resolve task before timeout (see sharedStateTaskTimeoutMs)",{task:t.payload,sharedStateTaskTimeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault});const i={uid:e,ts:Date.now(),pid:(0,B.processName)(),error:"timeout"};t.resolve(i)})),await this.read({setup:!0}),await ee.DirWatcher.for(this.dir,((e,t)=>p(this,n,"m",c).call(this,e,t)),J.EndableRanks.first)})),this.save=(0,K.oneAtATime)({fn:()=>{const e=this.currentState();return this.logger.info("save()",{state:e}),this.jsonFile.writeJson_(e)}}),this.jsonFile=e.join(i+".json"),(0,j.mapGt0)(ce.Settings.sharedStatePollMs.valueOrDefault,(e=>g(this,s,(0,S.setInterval)((()=>this.read()),e),"f"))),this.setup()}async read({files:e,setup:t}={}){(0,P.isEmpty)(e)&&(e=(0,N.toA)(await this.jsonFile.clearThisAndParent().siblings((e=>ye(e)))));const i=[];for(const t of e)if(ye(t)&&(0,ae.basename)(t)!==this.jsonFile.base&&await(0,le.isMtimeRecent)((0,ae.toNativePath_)(t),E.hourMs)){const e=await(0,oe.readFileMaybe)((0,ae.toNativePath_)(t)),n=(0,k.parseJSON)(e);null!=n&&i.push(n)}!0===t&&(0,de.pause)(i.some((e=>!0===e?.paused))),this.logger.debug("read()",{arr:i});let r=!1;if((0,P.isEmpty)(i))return;const s=Se((0,D.flatten)(i.map((e=>e.events))));this.logger.debug("read() events",{arr:i,events:s});for(const e of s)"taskResult"!==e.name&&"taskStarted"!==e.name||this.handledTaskUids.add(e.uid),r||(r=p(this,n,"m",f).call(this,e));r&&await this.save();const o=(0,D.flatten)(i.map((e=>e.tasks))),a=Date.now()-ce.Settings.taskTimeoutMs.valueOrDefault,l=(0,_.sortUniqBy)(o.filter((e=>(0,me.isStoredTask)(e)&&!this.handledTaskUids.has(e.uid)&&(0,F.gt)((0,q.tsFromUid)(e?.uid),a))),(e=>e.uid));(0,P.isNotEmpty)(l)&&this.logger.info("read()",{tasks:l}),this.handledTaskUids.addAll(l.map((e=>e.uid)));for(const e of l)p(this,n,"m",m).call(this,{task:e,sendEvents:!0,withFsLock:!0});p(this,n,"m",h).call(this,i)}vacuum(){(0,O.deleteIf)(p(this,a,"f"),((e,t)=>t.isSettled))}currentState(){return this.vacuum(),{pid:process.pid,paused:(0,de.isPaused)(),syncing:(0,B.isSyncService)()?(0,fe.isSyncing)():void 0,events:[...p(this,o,"f").values()],tasks:[...p(this,a,"f").values()].map((e=>e.payload))}}async maybeSave(){const e=this.currentState(),t=await this.jsonFile.readJson();(0,T.eql)(e,t)||await this.save()}async broadcast(e,...t){return this.broadcastEvent_({name:e,args:t})}async broadcastEvent_(e){const t={...e,uid:e.uid??(0,q.uid)()};this.logger.info("addEvent_()",{event:t});const i=(0,k.stringify)((0,L.pick)(t,"name","args"));return p(this,o,"f").set(i,t),this.handledEventUids.add(t.uid),this.eventEmitter.emit(t.name,...t.args),await this.save(),t}canHandleTaskLocally(e){return this.processors.some((t=>t.accept(e)))}submitTask_(e,...t){this.logger.info("submitTask_()",{name:e,args:t});const i={uid:(0,q.uid)(),name:e,args:t},r=new H.Deferred(e,{payload:i}).setTimeout(ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault);return this.canHandleTaskLocally(i)?r.observe(p(this,n,"m",m).call(this,{task:i,withFsLock:!1,sendEvents:!1})):(r.catch((e=>{this.broadcastEvent_({name:"taskResult",args:[{uid:i.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"uncaught rejection: "+(0,X.errorToS)(e)+Q.InternalErrorFlag}]})})),p(this,a,"f").set(i.uid,r),this.save(),r)}}t.SharedState=be,r=be,s=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(e,t){const i=(0,N.toA)(t).filter((e=>"delete"!==e.type&&!e.path.endsWith(v.sep+this.jsonFile.base))).map((e=>e.path));this.logger.debug("#onDirChange()",{files:i,_err:e,events:t}),this.read({files:i})},d=async function(){const e=(0,b.lazy)((()=>{this.logger.warn("#onEnd(): current state",this.currentState())}),10*E.secondMs);await(0,Y.untilTrue)((()=>{this.vacuum();const t=0===p(this,a,"f").size;return t||e(),t}),{timeoutMs:V.ShortCommandTimeoutMs,intervalMs:E.secondMs}),p(this,a,"f").destroy(),(0,I.map)(p(this,s,"f"),S.clearInterval),g(this,s,void 0,"f")},h=function(e){if(!(0,B.isWebService)())return;const t=e.filter((e=>e.syncing)).map((e=>e.pid));for(const e of t)if((0,y.pidExists)(e))return this.logger.debug("#updateSyncState(): syncing",{syncingPid:e}),void(0,fe.setIsSyncing)(!0);this.logger.debug("#updateSyncState(): no syncing states",{syncingPids:t}),(0,fe.setIsSyncing)(!1)},f=function(e){if(!we(e))return this.logger.warn("#handleRemoteEvent(): ignoring stale event",{event:e}),!1;if(this.handledEventUids.has(e.uid))return!1;if(this.handledEventUids.add(e.uid),this.logger.info("#handleRemoteEvent()",e),"resume"===e.name)(0,de.resume)();else if("pause"===e.name)(0,de.pause)();else{if("taskResult"===e.name){const t=e.args[0];if(!(0,me.isTaskResult)(t))return this.logger.warn("Invalid task result",{event:e}),!0;const i=p(this,a,"f").get(t.uid);return null!=i&&(this.logger.info("Received a task result for one of my tasks!",{event:e}),i.resolve(t)),!0}this.eventEmitter.emit(e.name,...e.args)}return!1},m=async function e({task:t,sendEvents:i,withFsLock:r}){const s=this.processors.filter((e=>e.accept(t)));if(0===s.length)return void this.logger.info("#handleTask(): no local task processor",{task:t});if(r)return(0,ie.withLock_)({name:"task-"+t.name+"-"+t.uid,file:this.dir.join(t.uid),timeoutMs:ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault,noopIfContested:!0},(()=>p(this,n,"m",e).call(this,{task:t,sendEvents:i,withFsLock:!1})));let o;s.length>1&&this.logger.warn("#handleTask(): multiple local task processors for "+t.name,{processors:s.map((e=>e.name))});for(const e of s)try{o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,result:await(0,A.thenOrTimeoutError)(e.apply(t),ce.Settings.sharedStateTaskTimeoutMs.valueOrDefault)},this.logger.info("#handleTask(): processor success",{processor:e.name,result:o,task:t});break}catch(i){this.logger.warn("#handleTask(): processor failed",{processor:e.name,error:i}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-"+e.name,error:(0,X.errorToS)(i)}}return null==o&&(this.logger.warn("#handleTask(): null result"+Q.InternalErrorFlag,{task:t}),o={uid:t.uid,ts:Date.now(),pid:(0,B.processName)()+"-error",error:"null result"+Q.InternalErrorFlag}),p(this,a,"f").get(t.uid)?.resolve(o),i?(this.logger.warn("#handleTask(): broadcasting result",{task:t,result:o}),await this.broadcastEvent_({name:"taskResult",args:[o]})):this.logger.warn("#handleTask(): NOT broadcasting result",{task:t,result:o}),o},l={value:(0,x.defer)((()=>{ce.Settings.libraryDir.watchLater(p(r,r,"f",u)),ce.Settings.cacheDir.watchLater(p(r,r,"f",u)),ce.Settings.sharedStateDir.watchLater(p(r,r,"f",u))}))},u={value:async()=>{const e=ce.Settings.sharedStateDir.valueOrDefault;(0,re.nativePathsEqlSync)(e,r.instance()?.dir)||(ge().warn("SharedState has changed. Restarting..."),await(0,G.end)(r.instance()),r.instance.refresh())}},be.instance=(0,b.lazy)((()=>{if((0,B.isWorkerService)())return void ge().warn("SharedState.instance() is not supported within worker services.",(0,C.shortStack)());p(r,r,"f",l).call(r);const e=(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>new r(se.PosixFile.for(e))));return null!=e&&ce.Settings.sharedStateTaskTimeoutMs.watchLater((t=>{e.handledEventUids.ttlMs=t,e.handledTaskUids.ttlMs=t,p(e,a,"f").ttlMs=t})),e})),t.submitTask_=function(e,...t){return be.instance()?.submitTask_(e,...t)},t.clearSharedStates=async function(){const e=be.instance.clear();await(e?.end());const t=e?.dir??(0,I.map)(ce.Settings.sharedStateDir.valueOrDefault,(e=>se.PosixFile.for(e)));await(t?.visitDescendants((e=>ve(e)?e.isDirectorySync()?e.rmdir():e.unlink():void 0)))}},79781:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clearTaskProcessors=t.addTaskProcessor=t.taskProcessors=void 0;const n=i(19658);t.taskProcessors=[],t.addTaskProcessor=function(e){t.taskProcessors.push(e)},t.clearTaskProcessors=function(){n.isTest&&(t.taskProcessors.length=0)}},44982:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(87561)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(40786),u=i(76531),c=i(51053),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const o=r??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return(!t||0!=(((u?256:0)|(f?32:0)|4)&e.mode))&&((!i||0!=(((u?128:0)|(f?16:0)|2)&e.mode))&&!(n&&!c.isWin&&0==(((u?64:0)|(f?8:0)|1)&e.mode)))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},77390:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(49411)),s=i(4866),o=i(91464),a=i(79141),l=i(51053),u=i(21084),c=i(3955),d=i(75123),h=i(35008);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,o.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},40786:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(87561),r=i(49411);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function a(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},98462:function(e,t,i){var n,r,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.useFsWatch=t.execDir=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44470)),p=c(i(87561)),g=i(93977),y=f(i(49411)),v=f(i(97742)),w=i(76402),S=f(i(47261)),b=f(i(65628)),P=i(4866),_=i(11944),M=i(92585),E=i(39938),x=i(88491),T=i(24603),C=i(1429),D=i(87748),k=i(66776),O=i(75556),I=i(61570),F=i(98510),L=i(65113),A=i(44726),N=i(39784),R=i(82798),j=i(13779),B=i(34996),V=i(46852),z=i(7383),W=i(21142),U=i(83486),q=i(49379),H=i(79015),G=i(79378),J=i(7162),$=i(6667),K=i(51053),Y=i(91464),Z=i(2073),X=i(69301),Q=i(24586),ee=i(44982),te=i(77390),ie=i(51081),ne=i(57400),re=i(93033),se=i(21084),oe=i(59873),ae=i(94329),le=i(3955),ue=i(1391),ce=i(27175),de=i(75123),he=i(35008),fe=i(95725),me=i(76531),pe=i(63410),ge=i(45512),ye=i(48500),ve=i(47987),we=i(95998);t.isBaseFile=function(e){return(0,fe.isSimpleFile)(e)&&e instanceof be};const Se=(0,P.lazy)((()=>new se.FileCache({name:"fs.BaseFile"})));class be{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((()=>(0,V.thenMap)(this.directoryEntry(),(e=>e.children()))))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,le.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ue.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,o=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof be?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof be)return e;const i=(0,fe.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=Se().get(i);if(null!=n)return n;const r=(0,he.resolve)(i),s=new be(r,t);return Se().set(i,s),Se().set(r,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return be.for(e,t)}forDirectoryEntry(e){return be.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,le.eqlPath)(this,e)}get isUNC(){return(0,le.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,le.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,le.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,de.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e))))),[])}childFilesSync(){return(0,k.orElse)(this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name))))),[])}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,N.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,le.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,X.bname)(this.name)]}get pathnamesWithoutDrive(){return K.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,le.pathDepth)(this)}get isRoot(){return(0,le.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,le.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,le.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,fe.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,te.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,le.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,C.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,z.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i="warn"){try{return(0,z.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i,`${e}() failed: ${t}`)}}stat_(){return(0,me.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,me.statMaybe)(this.nativePath,e?.logLevel),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,me.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,ee.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,ee.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,ee.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,ee.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,ee.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,ee.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,ee.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${K.isWin?"":"/execute"} by ${await(0,Q.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,le.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}isDirectory(e){return null!=this.dirent?this.dirent.isDirectory():(0,V.thenMapOr)(this.stat(e),(e=>e.isDirectory()),(()=>!1))}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat();return null!=e&&e.isFile()}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,le.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,W.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,le.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,G.parseJSON)((await m.readFile(this.nativePath)).toString())}readJson(e="warn"){return this.trap("readJson",(()=>this.readJson_()),e)}readJsonSync(){return this.trapSync("readJsonSync",(()=>(0,G.parseJSON)(p.default.readFileSync(this.nativePath).toString())))}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,we.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}async writeJson(e,t){return this.trap("writeJsonMaybe",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,le.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ye.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ye.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>{m.unlinkSync(this.nativePath),this.clearThisAndParent()}),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,re.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,re.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new ae.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,z.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ge.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,O.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs,!e.persistent),Pe)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,k.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=be,s=async function(){const e=(await(0,de.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},be.attrTTL=3*x.minuteMs,be.projectRoot=(0,P.lazy)((()=>{const e=ce.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return be.for(e)})),t.execDir=function(){return be.for(v.default.execPath).parent()};let Pe=!0;t.useFsWatch=function(e){Pe=e}},51081:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(11944),r=i(1429),s=i(44726),o=i(82798),a=i(51053);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},94488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(49411),r=i(4866),s=i(9678),o=i(7162),a=i(3955),l=i(53755),u=i(95725),c=i(76531),d=i(47987);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,o.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file is a cache directory tag",`# created by ${(0,s.AppNameVersion)()}`)}},88462:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(39938),l=i(15203),u=i(51053),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},30114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const n=i(1487),r=i(4866),s=i(11944),o=i(91641),a=i(95557),l=i(46852),u=i(17875),c=i(51498),d=i(7162),h=i(3955),f=i(95725),m=i(76531),p=i(76333),g=(0,r.lazy)((()=>(0,d.mkLogger)("fs.DirWatcher")));class y extends a.EndableWrapper{static async for(e,t,i=o.EndableRanks.first){const r=(0,f.toNativePath_)(e);await(0,h.mkdirp_)(r);const a=new c.FifoCache(1024),d=await(0,n.subscribe)(r,(async(e,i)=>{g().trace("callback",{nativePath:r,err:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:r}),null!=i&&(i=await(0,l.filterAsync)({name:this.name,arr:i,f:async e=>{if(e.path.includes(p.WipPrefix))return!1;const t=a.get(e.path),i=await(0,m.statMaybe)(e.path);return!(!0===i?.isFile()&&(0,m.statEql)(t,i)||(a.set(e.path,i),0))}})),(null!=e||(0,s.isNotEmpty)(i))&&t(e,i)}));return new y(r,d,a,i)}constructor(e,t,i,n){super("fs.DirWatcher("+e+")",(()=>this.close()),n),this.nativePath=e,this.subscription=t,this.path2stat=i,this.close=(0,r.lazy)((()=>this.subscription.unsubscribe()))}clear(){this.path2stat.clear()}}t.DirWatcher=y},57400:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44470)),l=o(i(87561)),u=i(49411),c=i(47261),d=i(4866),h=i(39784),f=i(7162),m=i(91464),p=i(79015),g=i(3955),y=i(75123),v=i(13594),w=i(95725),S=i(76531),b=i(63410);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await a.stat(t);return new M(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},93033:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(49411)),s=i(65113),o=i(3955),a=i(76531),l=i(63410);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(n.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},21084:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(11944),a=i(39938),l=i(43947),u=i(61570),c=i(91641),d=i(95557),h=i(79015),f=i(31737),m=i(7162),p=i(2023),g=i(14889);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},25015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkExtsRegExp=t.extAliases=t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.isExt=t.normalizeExt=void 0;const n=i(87561),r=i(4866),s=i(1429),o=i(21040),a=i(61570),l=i(82798),u=i(703),c=i(95725),d=/(?:^\.?|.\.)(?[a-z\d]{2,4})$/i;function h(e){e=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:e;const t=(d.exec((0,l.toS)(e))?.groups?.ext??e)?.toLowerCase();return u.JpegExts.includes(t)?"jpg":t}function f(e,...t){return e=h(e),t.some((t=>h(t)===e))}t.normalizeExt=h,t.isExt=f,t.isJpegExt=function(e){return f(e,...u.JpegExts)},t.isJsonExt=function(e){return f(e,"json")},t.isCsvExt=function(e){return f(e,"csv")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,s.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return f(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes},t.extAliases=(0,r.lazy)((()=>{const e=new Map;for(const t of[u.JpegExts,["tif","tiff"],["heif","heic"],["html","htm"],["jp2","jp2k"]])for(const i of t)e.set(i,t);return e}));const m=new Map;t.mkExtsRegExp=function(e){return(0,o.getOrSet)(m,e.join(","),(()=>new RegExp("\\.(?:"+e.join("|")+")$","im")))}},99435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStats_=void 0;const n=i(93977),r=i(61570),s=i(95725);t.fileStats_=async function(e){return(0,r.pick)(await(0,n.stat)((0,s.toNativePath_)(e)),"size","mtimeMs")}},19653:function(e,t,i){var n,r,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},b=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const P=i(5712),_=b(i(44470)),M=i(92332),E=i(11944),x=i(37609),T=i(88491),C=i(24603),D=i(19067),k=i(66776),O=i(75556),I=i(23175),F=i(20636),L=i(82798),A=i(19658),N=i(1058),R=i(55568),j=i(91641),B=i(95557),V=i(4691),z=i(17354),W=i(53525),U=i(9483),q=i(6231),H=i(53719),G=i(95694),J=i(95725),$=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends B.EndableWrapper{static newUid(e=process.pid){return S(this,r,Math.max(Date.now(),w(this,r,"f",s)+1),"f",s),(0,E.compactBlanks)([q.TokenRadix.encode(w(this,r,"f",s)),R.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,O.toInt)($.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return w(this,r,"f",a).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>this.release()),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,S(t=r,r,(i=w(t,r,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,z.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(w(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await w(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+w(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),w(r,r,"f",a).push(this)}get acquired(){return w(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await w(this,n,"m",f).call(this,e)??w(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,C.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==w(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,A.isTest?10:T.secondMs);S(this,c,setInterval((()=>w(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=w(this,c,"f")&&(clearInterval(w(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(w(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.ended&&(0,E.filterInPlace)(w(r,r,"f",a),(e=>w(e,l,"f")!==w(this,l,"f"))),this.stopRefreshTimer(),S(this,u,!1,"f"),(0,k.map)(w(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync(U.LogLevels.trace),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?w(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>w(this,n,"m",v).call(this)),2*this.staleMs),"f"),w(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(w(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,F.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>w(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await w(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await w(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&ie.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!A.isTest)return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+W.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,P.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),w(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await w(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=function(){this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:this.lockdir.rmdirSync("trace")})},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();const i=new K(e);try{return await i.withLock_(t)}finally{i.end()}}},95694:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(39938),r=i(44726),s=i(82798),o=i(95725);function a(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&a((0,o.basename)(e))}},86472:function(e,t,i){var n,r,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FsWatcher=t.DefaultWatchedStatFields=void 0;const h=d(i(44470)),f=d(i(87561)),m=i(4866),p=i(38625),g=i(88491),y=i(43947),v=i(24603),w=i(75556),S=i(61570),b=i(20636),P=i(12308),_=i(28807),M=i(91641),E=i(17354),x=i(79015),T=i(3955),C=i(8177),D=i(43414),k=i(91464),O=i(37086),I=i(59873),F=i(95725),L=i(76531),A=i(63410);t.DefaultWatchedStatFields=["ino","size","mtimeMs","birthtimeMs"];class N extends _.EndableInterval{constructor(){super({name:"fs.WatchMgr",callback:()=>this.vacuum(),intervalMs:g.minuteMs,unref:!0}),this.path2watcher=new Map,this.id2watchers=new Map,this.onEnds.push((()=>{for(const[e,t]of this.path2watcher)try{t.close()}catch(t){this.logger.warn("failed to close FsWatcher for "+e,t)}}))}vacuumEnded(){for(const[e,t]of this.id2watchers)t.ended&&this.id2watchers.delete(e)}registeredPaths(){return new Set([...this.id2watchers.values()].map((e=>e.targetNativePath)))}watchedPaths(){return[...this.path2watcher.keys()]}vacuum(){this.vacuumEnded();const e=(0,C.diff)(this.watchedPaths(),this.registeredPaths());for(const t of e)try{this.logger.warn("closing orphaned FsWatcher for "+t),this.path2watcher.get(t)?.close(),this.path2watcher.delete(t)}catch(e){this.logger.warn("failed to close FsWatcher for "+t,e)}const t=(0,C.diff)(this.registeredPaths(),this.watchedPaths());for(const e of t)this.maybeWatch(e);this.logger.debug("vacuum() complete",{watchedPaths:[...this.watchedPaths()],registeredPaths:[...this.registeredPaths()],oldPaths:[...e],unwatchedPaths:[...t]})}maybeWatch(e){if(0===this.watchersForPath(e).length)throw new Error("no registered watchers for "+e);if(null==this.path2watcher.get(e)&&f.default.existsSync(e)){const t=this.watchersForPath(e),i=(0,p.or)(t.map((e=>e.args.persistent)));this.logger.info("Setting up fs.watch for "+e);const n=f.default.watch(e,{persistent:i},(()=>this.onChange(e)));this.path2watcher.set(e,n),n.on("close",(()=>{this.path2watcher.delete(e)})),n.on("error",(t=>{this.path2watcher.delete(e),this.logger.warn("fs.watch failed",{error:t,watchers:this.watchersForPath(e)?.filter((e=>!e.ended)).map((e=>e.name))})}))}}registerWatcher(e){this.id2watchers.set(e.id,e),this.maybeWatch(e.targetNativePath)}watchersForPath(e){const t=[];for(const i of this.id2watchers.values())(0,T.eqlPath)(i.targetNativePath,e)&&t.push(i);return t}onChange(e){for(const t of this.id2watchers.values())(0,T.eqlPath)(t.targetNativePath,e)&&t.debouncedCheck()}}N.instance=new N;class R extends _.EndableInterval{constructor(e){super({name:`fs.FileWatcher(${(0,F.toNativePath_)(e.target)})`,callback:()=>this.debouncedCheck(),intervalMs:e.maxPollIntervalMs,rank:M.EndableRanks.first,initialDelayMs:e.initialDelayMs}),n.add(this),this.args=e,this.id=(0,O.uid)(),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),this.setup=(0,m.lazy)((async()=>{const e=(0,A.statSync)(this.targetNativePath);return u(this,r,null==e?void 0:(0,S.pick)(e,...t.DefaultWatchedStatFields),"f"),!0===e?.isDirectory()&&await c(this,n,"m",a).call(this),!0===e?.isFile()&&await c(this,n,"m",l).call(this),this.logger.info("setup()",{stat:c(this,r,"f"),sha:c(this,s,"f"),children:c(this,o,"f")}),null!=e&&!0===this.args.applyOnChangeAtSetupIfExists&&this.args.onChange(),this})),this.debouncedCheck=(0,P.debounce)((()=>this.check()),this.args.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault),this.check=(0,E.oneAtATime)({fn:async()=>{if(this.ended)return;this.logger.debug("check(): starting",{prior:c(this,r,"f")});const e=c(this,r,"f"),i=await(0,L.statMaybe)(this.targetNativePath);if(null==i)return null!=c(this,r,"f")&&!0===this.args.applyOnChangeIfTargetMissing&&this.args.onChange(),this.logger.debug("check(): missing stat, closing file watcher"),void this.reset();(0,y.later)((()=>N.instance.registerWatcher(this)));const s=(0,S.pick)(i,...t.DefaultWatchedStatFields),o=(0,v.eql)(e,s),d=i.isDirectory()?await c(this,n,"m",a).call(this):!o&&!!i.isFile()&&await c(this,n,"m",l).call(this);this.logger.debug(".check()",{changed:d,partialStatNow:s,partialStatPrior:e,isDir:i.isDirectory(),isFile:i.isFile()}),d&&((0,x.ee)().emit("fileChanged",this.targetNativePath),u(this,r,s,"f"),this.args.onChange())}}),this.targetNativePath=(0,F.toNativePath_)(e.target);const i=e.watchDebounceMs??D.Settings.watchDebounceMs.valueOrDefault,d=e.maxPollIntervalMs;(0,w.gt0)(d)&&d<=i&&(e.maxPollIntervalMs=i+100,this.setIntervalMs(e.maxPollIntervalMs),this.logger.error("Bad configuration: watchDebounceMs must be less than maxPollIntervalMs. Increasing maxPollIntervalMs.",{watchDebounceMs:i,maxPollIntervalMs:d,newMaxPollIntervalMs:e.maxPollIntervalMs})),this.onEnds.push((()=>{this.reset(),(0,y.later)((()=>N.instance.vacuum()))})),this.logger.debug("new FsWatcher()",{watchDebounceMs:i,maxPollIntervalMs:e.maxPollIntervalMs}),this.setup(),N.instance.registerWatcher(this)}get partialStatPrior(){return c(this,r,"f")}get debounceMs(){return this.debouncedCheck.timeoutMs()}forcedCheck(){return this.debouncedCheck.reset(),this.check.force()}reset(){u(this,r,void 0,"f"),u(this,s,void 0,"f"),u(this,o,void 0,"f")}}t.FsWatcher=R,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=async function(){const e=await(0,b.thenOrTimeout)(h.default.readdir(this.targetNativePath),D.Settings.statTimeoutMs.valueOrDefault);if(e===b.Timeout)return this.logger.warn("Failed to read directory: timeout",{timeoutMs:D.Settings.statTimeoutMs.valueOrDefault}),u(this,o,void 0,"f"),!1;const t=(0,k.sortIgnoreCase)(e);return!(0,v.eql)(c(this,o,"f"),t)&&(this.logger.debug("checkDirChanged(): children changed",{now:t,prior:c(this,o,"f")}),u(this,o,t,"f"),!0)},l=async function(){if(!0!==this.args.sha)return!0;const e=await(0,I.fileSha_)(this.targetNativePath).catch((()=>{}));return(null==e||e!==c(this,s,"f"))&&(u(this,s,e,"f"),!0)}},81666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(39938),r=i(66776),s=i(75556),o=i(44726),a=i(82798),l=i(70283),u=i(3955),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},59873:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(6005)),s=n(i(87561)),o=i(76402),a=i(4866),l=i(24603),u=i(87748),c=i(61570),d=i(31737),h=i(24588),f=i(7162),m=i(13378),p=i(29731),g=i(99435),y=i(95725),v=i(76531),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,l.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,c.pick)(await(0,v.stat_)(i),"size","mtimeMs"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,o.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},64546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(4866),r=i(88491),s=i(66776),o=i(75556),a=i(69317),l=i(79015),u=i(51053),c=i(71663),d=i(53719),h=i(98462),f=i(21084),m=i(95725),p=i(76531);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,m.toNativePath_)(e);await(0,p.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const g=(0,n.lazy)((()=>new f.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,d.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux)return!1;const t=(0,m.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?g().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&g().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},28119:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(39938),r=i(82798),s=i(19658),o=i(51053),a=i(10609),l=/^\/dev(?:\/|$)/i,u=o.isMac||s.isTest?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||s.isTest?/^\/private\//i:void 0,d=o.isMac||s.isTest?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||s.isTest?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},703:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},94329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(84492),r=i(44726),s=i(82798);class o extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),o=n.pop();this._prior=o??"";let a=!1;for(const e of n)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},35694:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(49411)),s=i(95725),o=i(47987);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},95741:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const n=i(77390),r=i(95725);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,r.toNativePath_)(e),n=(0,r.toNativePath_)(t);return null!=i&&null!=n&&i===n}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,n.actualPath_)((0,r.toNativePath_)(e))===await(0,n.actualPath_)((0,r.toNativePath_)(t))}catch{return!1}}},28659:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.hasNoMedia=t.isNoMedia=t.hasNoMediaRecursive=t.isNoMediaName=void 0;const o=s(i(49411)),a=i(4866),l=i(25452),u=i(7162),c=i(9483),d=i(98462),h=i(94488),f=i(21084),m=i(75123),p=i(95725),g=i(76531),y=(0,a.lazy)((()=>(0,u.mkLogger)("fs.hasNoMedia()"))),v=/^\.?NoMedia$/i,w="NoMedia";function S(e){return[e,e.toLowerCase(),e.toUpperCase()]}const b=Object.freeze([...S("."+w),...S(w)]);function P(e){return null!=v.exec(e)}t.isNoMediaName=P;const _=(0,a.lazy)((()=>new f.FileCache({name:"fs.noMediaDirsCache"})));async function M(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return t.base===h.CACHEDIR_TAG?y().tap({msg:t.nativePath+" is a CACHEDIR.TAG file",result:await(0,h.isCachedirTagFile)(t)}):P(t.base)?y().tap({msg:t+" basename is NoMedia",result:!0}):!!await t.isDirectory()&&_().getOrSetAsync(t.nativePath,(()=>async function(e){const t=new l.Halt,i=(0,m.readdirCached)(e);if(null!=i)return x(e,i,t);const n=await Promise.race([E(e,t),T(e,t)]);return t.halt(),n}(t.nativePath)))}async function E(e,t){for(const i of b){if(!0===t?.halted)return null;if(await(0,g.exists)(o.default.join(e,i),c.LogLevels.trace))return y().tap({msg:e+" is a directory and has a noMedia child, "+i,result:!0})}return!0===t?.halted?null:(0,h.isCachedirTagDirectory)(e)}async function x(e,t,i){for(const n of t){if(!0===i?.halted)return null;if(P(n.basename))return y().tap({msg:e+" has a noMedia child, "+n.basename,result:!0});if(n.basename===h.CACHEDIR_TAG&&await(0,h.isCachedirTagFile)((0,o.join)(e,n.basename)))return!0}return!1}async function T(e,t){const i=await(0,m.readdir)(e);return null!=i&&x(e,i,t)}t.hasNoMediaRecursive=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return(0,p.someSelfOrAncestor)(t,M)},t.isNoMedia=async function(e){if(null==e)return!1;const t=(0,p.isSimpleFile)(e)?e:d.BaseFile.for(e);return P(t.base)||await(0,h.isCachedirTagFile)(t)},t.hasNoMedia=M},3955:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(92585),u=i(39938),c=i(87748),d=i(44726),h=i(13779),f=i(7162),m=i(91464),p=i(49379),g=i(51053),y=i(1391),v=i(35008),w=i(95725),S=i(76531),b=i(63410),P=i(1963);function _(e){return((0,w.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return D(e).some(_)},t.isNotHiddenPosixPath=function(e){return D(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,y.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return s.default.dirname((0,w.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,m.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function x(e){const t=s.default.parse((0,w.toNativePath_)(e));return t.root===t.dir?t.root:(0,d.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,w.toNativePath_)(e.ancestor),i=(0,w.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,m.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function C(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(g.isLinux?n===r:(0,m.equalsIgnoreCase)(n,r))}function D(e){return(0,w.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function k(e){return e.startsWith("\\\\")}function O(e){return(0,d.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),g.isWin?"":s.default.sep)}t.parseNativePath=E,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,w.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return C(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return C(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return C(w.toNativePath_,e,t)},t.toPathnames=D,t.pathIsRoot=function(e){return(0,u.notBlank)(e)&&D(e).length===(g.isWin?1:0)},t.pathDepth=function(e){return(0,u.blank)(e)?void 0:D(e).length-(g.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),n=(0,w.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,m.stripPrefix)((0,y.native2posix)(n).normalize(),(0,m.ensureSuffix)((0,y.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=function({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const n=D(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),O([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("โ€ฆ"),O([...r,...s])},t.posixPathFromParent=function(e){return D(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return D(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=k,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(k(e)||null!=e.match(P.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;await r.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,b.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,b.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,w.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},9288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(49411)),s=i(4866),o=i(11944),a=i(39938),l=i(75556),u=i(44726),c=i(17078),d=i(39784),h=i(82798),f=i(7162),m=i(29405),p=i(20902),g=i(15203),y=i(51053),v=i(44982),w=i(77390),S=i(76531),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},98250:function(e,t,i){var n,r,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44470)),h=c(i(87561)),f=c(i(93977)),m=c(i(49411)),p=i(76402),g=i(4866),y=i(11944),v=i(59694),w=i(92585),S=i(39938),b=i(88491),P=i(16475),_=i(19067),M=i(66776),E=i(75556),x=i(61570),T=i(20636),C=i(49049),D=i(17078),k=i(82798),O=i(13779),I=i(7162),F=i(14889),L=i(91464),A=i(46852),N=i(7383),R=i(21142),j=i(69317),B=i(14195),V=i(53525),z=i(49379),W=i(9483),U=i(6231),q=i(51053),H=i(49586),G=i(71663),J=i(43414),$=i(78362),K=i(3874),Y=i(19209),Z=i(25116),X=i(32421),Q=i(53719),ee=i(46573),te=i(98462),ie=i(21084),ne=i(25015),re=i(19653),se=i(64546),oe=i(35694),ae=i(28659),le=i(3955),ue=i(95725),ce=i(83837),de=i(48500),he=i(76333),fe=i(95998),me=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class pe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return pe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?pe.for(e):void 0}static for(e,t){if(e instanceof pe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=me().get(e);if(null!=t)return t}const i=(0,ue.toNativePath_)(e),n=new pe(i,t);return(0,L.isString)(e)&&me().set(e,n),me().set(i,n),n}static forPosix(e){return pe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>pe.for(e)))}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,le.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,le.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?pe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>pe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===C.PS_LIBRARY_SCHEME?1:t.scheme===C.PS_LOCAL_FILE_SCHEME?2:t.scheme===C.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async mkNoMedia_(){return(0,oe.mkNoMedia_)(this)}async mkNoMedia(){try{return await this.mkNoMedia_(),this}catch(e){return void this.pflog().warn("Could not add .NoMedia file to "+this,e)}}hasNoMedia(){return(0,ae.hasNoMedia)(this)}hasNoMediaRecursive(){return(0,ae.hasNoMediaRecursive)(this)}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new ce.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:o,minSizeBytes:i,timeoutMs:r,dirty:l})}return a&&n?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,L.ensurePrefix)(this.base,he.WipPrefix))}isWip(){return this.name.startsWith(he.WipPrefix)}async wipIsRecent(e=he.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwipBase(){return(0,L.stripPrefix)(this.base,he.WipPrefix)}unwip_(){return this.mv_(this.sibling(this.unwipBase()))}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){return await e.parent().mkdirp_(),await(0,fe.zpipe_)(this.nativePath,h.default.createWriteStream(e.nativePath,{autoClose:!0}),t),e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,le.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,le.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=pe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(r.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,de.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,de.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},1391:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(49411)),s=i(39938),o=i(91464);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,o.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},27175:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=t.execDir=void 0;const r=n(i(49411)),s=n(i(97742)),o=i(4866),a=i(11944),l=i(13779),u=i(7162),c=i(15203),d=i(51053),h=i(40786),f=i(28119);function m(...e){return(0,o.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.execDir=(0,o.lazy)((()=>r.default.dirname(s.default.execPath))),t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],i=[];(0,c.isDocker)()&&i.push("/opt/photostructure"),d.isElectron&&i.push(r.default.join((0,t.execDir)(),"resources"),r.default.join((0,t.execDir)(),"..","Resources")),i.push(...(0,a.compactBlanks)([(0,t.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(i);for(const t of i){if((0,h.hasChildrenSync)(t,e))return t;for(const i of(0,h.ancestors)(t).slice(0,4)){if((0,h.hasChildrenSync)(i,e))return i;const n=r.default.join(t,"node_modules","photostructure");if((0,h.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+i)})),Bin:m("bin"),Data:m("data"),ICC:m("data","icc"),Migrations:m("data","migrations"),Public:m("public"),Tools:m("tools"),Views:m("views"),isInDMG:function(e){return!!d.isMac&&(0,f.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},4931:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44470),r=i(4866),s=i(75556),o=i(7162),a=i(9483),l=i(41544),u=(0,r.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},53755:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44470),r=i(70283);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,o=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,o,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},41544:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(87561));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},13348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44470),r=i(51081);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},96895:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(84492);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},75123:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(93977)),s=i(49411),o=i(4866),a=i(59694),l=i(39938),u=i(88491),c=i(43947),d=i(75556),h=i(20636),f=i(32614),m=i(7162),p=i(49273),g=i(79015),y=i(43414),v=i(53719),w=i(21084),S=i(84571);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(y.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const b=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Readdir")));async function P(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){b().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=P;const _=(0,o.lazy)((()=>new w.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return b().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),n=x(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(y.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(r===h.Timeout&&(0,p.onTimeout)({soft:!1}),r!==h.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{y.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,g.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),P()))),(0,g.ee)().on("fileChanged",(e=>(0,l.blank)(e)?P():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new f.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return await((0,d.gt0)(y.Settings.readdirCacheMs.valueOrDefault)?E(e):x(e))}catch(t){return void b().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},35008:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolve=void 0;const r=n(i(49411)),s=i(39938),o=i(1963);t.resolve=function(...e){if((0,s.blank)(e.join("")))throw new Error("resolve(): empty paths");return r.default.resolve((0,o.upcaseDriveLetters)(e[0]),...e.slice(1))}},13594:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(39938),r=i(38625);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},95725:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.isSimpleFile=void 0;const r=n(i(87561)),s=n(i(49411)),o=i(39938),a=i(87748),l=i(91464),u=i(51053),c=i(3955),d=i(35008),h=i(13594);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){if((0,a.blank)(e))return v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1});const t=Date.now();try{return await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,y.statTimeoutMs)(),!0)}finally{const i=Date.now()-t;i>(0,y.statTimeoutMs)()/2&&(v().warn("soft timeout for "+e,{elapsedMs:i}),(0,h.onTimeout)({soft:!0}))}}function S(e,t=m.LogLevels.debug){return(0,a.blank)(e)?void 0:w(e).catch((i=>{v().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function P(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function _(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" โ‰  "+(null==t?"null":"stat");const i=b(e),n=b(t);if(i!==n)return"inconsistent file type: "+i+" โ‰  "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(P(n),P(r));if(null==s||s>1)return"unmatched "+i+": "+n+" โ‰  "+r}}t.stat_=w,t.statMaybe=S,t.statToType=b,t.whyStatNotEql=_,t.statEql=function(e,t){return null==_(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,p.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await S(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},63410:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isDirectorySync=t.isEmptyStats=t.isMtimeRecentSync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.nativePathSizeSync=t.nativePathExistsSync=t.statSync=void 0;const r=n(i(87561)),s=i(49411),o=i(39938),a=i(80294),l=i(44982),u=i(1391);function c(e){if(!(0,o.blank)(e))try{return r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function d(e){if((0,o.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}function h(e){return null==e||e.isFile()&&0===e.size}function f(e){return!0===c(e)?.isDirectory()}t.statSync=c,t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return c(e)?.size},t.isFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=c(e);return t.emptyIsNew?null==i:h(i)},t.isNonEmptyFileSync=function(e,t=0){const i=c(e);return null!=i&&i.isFile()&&i.size>=t},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)(c(e)?.mtimeMs,t)},t.isEmptyStats=h,t.isDirectorySync=f,t.isReadableDirectorySync=function(e){const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=c(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if(f(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},84571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(43414);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},45512:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(39938),r=i(6314);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},18991:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},83837:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(84492)),s=i(43947),o=i(66776),a=i(61570),l=i(90957),u=i(2023),c=i(4691),d=i(49379);class h extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=h,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50),(0,u.Try)((()=>(0,a.maybeCall)(e,"destroy"))))},t.closeStream=async function(e){null!=e&&((0,u.Try)((()=>(0,a.maybeCall)(e,"unref"))),(0,c.ending)()?e.close(l.NoOp):await new Promise((t=>e.close(t))))},t.onChildError=function(e,t){[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}].forEach((({name:e,ea:i})=>(0,o.map)(i,(i=>i.on("error",(i=>{!1===(0,d.isIgnorableError)(i)&&t(e,i)}))))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},48500:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44470)),s=i(4866),o=i(39938),a=i(88491),l=i(75556),u=i(61570),c=i(20636),d=i(3955),h=i(95725),f=i(76531),m=i(84571);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},1963:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(49411)),s=i(82798);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},76333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(39938),r=i(14889),s=i(95725);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.isWip=function(e){return!(0,n.blank)(e)&&(0,s.basename)(e).startsWith(t.WipPrefix)}},16414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(84492),r=i(34996);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},47987:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44470)),s=n(i(49411)),o=i(44726),a=i(82798),l=i(79015),u=i(51081),c=i(3955);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},95998:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(87561)),s=i(49411),o=i(76402),a=i(65628),l=i(4866),u=i(11944),c=i(87748),d=i(79378),h=i(7162),f=i(79141),m=i(3955),p=i(9483),g=i(96895),y=i(16414),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},6565:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(84253);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},80534:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(84253);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},49441:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(93977),r=i(4866),s=i(88491),o=i(39784),a=i(82798),l=i(7162),u=i(19658),c=i(91464),d=i(29731),h=i(10742),f=i(1629),m=i(42648),p=i(79015),g=i(98250),y=i(95725),v=i(6231),w=i(53719),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:u.isTest?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:u.isTest?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:o}),o}t.rmImageCacheDir=async function(){if(u.isProd)throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},86613:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(84253);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},74269:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(4866),r=i(55568),s=i(95976),o=i(98968);class a{log(e,t,i,n){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}end(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,n.lazy)((()=>new a))},78109:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(39938),r=i(16475),s=i(66776),o=i(61570),a=i(47025),l=i(7162),u=i(70283),c=i(14889),d=i(78342),h=i(4691),f=i(79141),m=i(9483);class p{constructor(e,t=l.rootLoggers){this.loggers=t,this.error=(e,t)=>{this.log("error",e,t)},this.warn=(e,t)=>{this.log("warn",e,t)},this.info=(e,t)=>{this.log("info",e,t)},this.debug=(e,t)=>{this.log("debug",e,t)},this.trace=(e,t)=>{this.log("trace",e,t)},this.context=(0,n.toNotBlank)(e)??(0,r.shortStack)().find((e=>!e.includes("Logger")))??""}toLogJSON(){return"CtxLogger("+this.context+")"}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted(e){if((0,h.ending)()||!0===e?.aborted){const t=(0,h.ending)()?"service ending":e?.reason??"(no reason given)";throw this.warn("process aborted: "+t),new d.AbortError(t)}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),c.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,s.map)(i,clearTimeout)}}async tapAsync(e){const t=e.level??(0,u.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;try{const i=await((0,a.isFunction)(e.result)?e.result():e.result);return this.log(t,e.msg,{result:i,...e.meta}),i}catch(t){throw this.log(e.errorLevel??"warn",e.errorMsg??e.msg+" failed",{error:t,...e.meta}),t}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}async end(){for(const e of this.loggers())await e.end()}}t.ContextualLogger=p},71951:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(4866),r=i(27998);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},85352:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=250},77200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(59694),r=i(75556),s=i(44726),o=i(9483);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},95976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(4866),r=i(9483);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},9483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(88491),r=i(75556),s=i(84253);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=7*n.secondMs){return e>=t?"error":e>=t/2?"warn":e>=t/4?"info":"debug"}},98968:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(55413),r=i(58623),s=i(71951),o=i(85352),a=i(77200);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},27998:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(47261),r=i(11944),s=i(66776),o=i(61570),a=i(82798),l=i(55568),u=i(91464),c=i(9483);t.PlaintextLogFormatter=class{constructor(e={colors:!1,depth:4,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},60346:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(47261),a=i(11944),l=i(1429),u=i(66776),c=i(75556),d=i(61570),h=i(39784),f=i(13779),m=i(24945),p=i(94383),g=i(70283),y=i(6667);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new v).pushAll(e).stats()};class v{static merge(e,t){if(0===e.n&&0===t.n)return new v(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new v(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,y.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new v).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,y.min)([this._min,e.min]),this._max=(0,y.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new v(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,y.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,y.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,y.avg)}get sampleSlope(){return(0,u.orElse)((0,a.mapNotEmpty)(this._samples,y.slope),0)}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,y.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=v,r=function(e){return(0,g.mapGte0f)(this.avg,(t=>(0,g.mapGte0f)(this.stdDev,(i=>(0,c.sigFigs)(t+i*e,4)))))}},70208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(11944),r=i(66776),s=i(75556),o=i(23175),a=i(13779),l=i(6667);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):n[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},43649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(59694);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,n.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return r(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},6231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(6005),r=i(39938),s=i(66776),o=i(47025),a=i(2023),l=i(91464),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},69547:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0,t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:e?.eventsPerSecond,msSinceLastEvent:e?.msSinceLastEvent}}},76474:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(6005),r=i(3331);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},6667:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(11944),l=i(66776),u=i(75556),c=i(39784),d=i(94383),h=i(8177),f=i(60346);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),o(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+o*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},18501:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(70612)),s=i(4866),o=i(39938),a=i(43947),l=i(91464),u=i(43414);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},58659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(30604),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(75556),u=i(20636),c=i(82798),d=i(7162),h=i(70283),f=i(14889),m=i(91464),p=i(97503),g=i(46852),y=i(79015),v=i(94517),w=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,p.memoizeAsync)((async e=>{const i=null==w.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:f.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=S.exec(e)}function P(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=b,t.octets=P,t.resolve4=(0,p.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=P(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,r.lazy)((()=>(0,d.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,y.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,p.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=P(e)?n.promises.reverse(e):n.promises.resolve4(e),5*o.secondMs);if(t===u.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,m.equalsIgnoreCase)(e,i)||!(!b(e)||!b(i))||(0,g.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},94517:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(39938),r=i(88491),s=i(75556),o=i(98510),a=i(82798),l=i(97503),u=i(69317),c=i(9288),d=i(51053),h=i(14889);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},15203:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(87561),r=i(38625),s=i(4866),o=i(60052),a=i(51053);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,r.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},94845:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(49411),r=i(4866),s=i(82798);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},51053:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(70612)),s=n(i(97742)),o=i(39938),a=i(38625),l=i(60052),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},33407:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(87561)),s=i(4866),o=i(51053);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},24409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(11944),r=i(39938),s=i(75556),o=i(3955),a=i(70283);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},29663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(4866),r=i(88491),s=i(75556),o=i(13378),a=i(3917),l=i(79015),u=i(24409);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new a.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new a.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},49586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(87748),r=i(75556),s=i(99869),o=i(28807),a=i(91641),l=i(4691),u=i(46852),c=i(10408),d=i(29663);class h extends o.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{this.logger.warn("failed: ",e),this.ctx.op+=" (failed: "+(0,c.errorToS)(e,{maxLen:128})+")",this.end()})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},71663:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(5712),r=i(4866),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(20636),c=i(13056),d=i(70403),h=i(7162),f=i(19658),m=i(14889),p=i(91464),g=i(91641),y=i(95557),v=i(4691),w=i(46852),S=i(21142),b=i(69317),P=i(79015),_=i(51053),M=i(43414),E=i(53719),x="{ready}",T=" | ConvertTo-Json -Compress";function C(e){return'"'+e.replace(/['`"โ€œโ€#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=C,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if(f.isTest&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+C(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,r.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>(0,l.orElse)(e.lastStartError,e.lastTaskError)),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},1440:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(84253);t.AggregateTypes=(0,n.strEnum)("union","intersection")},92187:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(84253);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},79660:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(39938),r=i(38625),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=o},29712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},26764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(98510),o=i(84161);class a extends o.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},48995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(84253);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},18947:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},92438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},22130:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(42885),r=i(77696),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},95888:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=o},7043:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=o},29909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},88256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(39938),r=i(35008),s=i(99088);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23753:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=o},46062:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(39938),r=i(75556),s=i(84161);class o extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},99088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},84490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(44726),r=i(63774);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},84161:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const n=i(4866),r=i(11944),s=i(37589),o=i(24603),a=i(51367),l=i(87748),u=i(66776),c=i(61570),d=i(65113),h=i(71756),f=i(90957),m=i(39784),p=i(32843),g=i(91464),y=i(29405),v=i(20902),w=i(79015),S=i(84490),b=i(44911),P=i(38049),_=i(16704);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){this.opts=e,this._envValue=(0,n.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}normalizeValue(e){return null==e?void 0:this.opts.fromEnv(this.opts.toEnv(e))}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._userValue??this._envValue()}set envValue(e){this.onChange(e,(e=>{this._envValue.set(e),this.addToEnv()}))}refreshEnvValue(e={}){const t=(0,s.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}readFromEnv(e){const t=null==e?(0,v.caseInsensitiveEnv)():new p.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,u.map)(t.get(e),(e=>this.opts.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,y.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,r.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,w.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,s.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,o.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,r.uniq)([e,...(0,m.toA)(this.opts.aliases)]),this._key=(0,S.envFromName)(e),this._keys=(0,r.uniq)([...this._names.map(S.envFromName),this._key,...(0,m.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return b.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,u.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.opts.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,f.tot)(this.optsOverrides.defaultValue)??(0,f.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,s.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,f.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,y.env)(),n=this.envValue??t;return null!=n&&(i[this.key]=this.opts.toEnv(n)),null==e&&v.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.opts.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,y.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&v.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,u.map)(e,(e=>new p.CaseInsensitiveValued(e)))??(0,v.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys])t.delete(e);return t.obj}unset(){return this.onChange(void 0,(()=>{this._userValue=void 0,this._envValue.unset(),this._fileValue=void 0,this._tmpValue=void 0,this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,g.wrap)([(0,d.padding)("-",e.length),e,(0,d.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],_.WrapComments);function i(e,i){(0,r.isEmpty)(i)||t.push(...(0,g.wrap)(["",(1===i.length?e:(0,h.pluralize)(e))+": "+(0,a.orList)(i.map((e=>(0,l.stringify)(e))))],_.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,c.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,a.orList)(i.map((e=>(0,l.stringify)(e)))):(0,l.stringify)(i);t.push(...(0,g.wrap)(["",e+": "+n],_.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,u.map)(e,(e=>this.opts.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Example value:"],key:this.name,value:(0,f.tot)(this.exampleValue)}),(0,P.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Default value:"],key:this.name,value:(0,f.tot)(this.defaultValue)}),(0,P.wrapTomlToLines)({lines:e,key:this.name,value:(0,f.tot)(this.fileValue)}),e}}},44911:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(84253);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Events","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Events,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},43414:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(5712),r=i(49411),s=i(4866),o=i(11944),a=i(59694),l=i(39938),u=i(88491),c=i(97042),d=i(61570),h=i(84253),f=i(17078),m=i(82798),p=i(36218),g=i(32843),y=i(71215),v=i(21941),w=i(19658),S=i(86725),b=i(6344),P=i(42885),_=i(27387),M=i(29393),E=i(94794),x=i(7560),T=i(45005),C=i(20902),D=i(6565),k=i(80534),O=i(86613),I=i(15203),F=i(51053),L=i(33407),A=i(11579),N=i(82590),R=i(55267),j=i(98788),B=i(61659),V=i(40185),z=i(32994),W=i(39036),U=i(86115),q=i(36738),H=i(17679),G=i(75153),J=i(1440),$=i(92187),K=i(79660),Y=i(29712),Z=i(26764),X=i(48995),Q=i(18947),ee=i(92438),te=i(22130),ie=i(95888),ne=i(7043),re=i(29909),se=i(88256),oe=i(23753),ae=i(46062),le=i(99088),ue=i(44911),ce=i(70338),de=i(35195),he=i(39165),fe=i(24354),me=i(96879);t.isProd=(0,s.lazy)((()=>w.isProd));const pe=()=>!(0,t.isProd)();function ge(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function ye(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new se.OptionalFileSetting({aliases:["libraryPath","library"],category:ue.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new fe.StringSetting({aliases:["originalDir"],category:ue.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new ce.StringArraySetting({aliases:["scanPath"],category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new ce.StringArraySetting({category:ue.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new le.OptionalStringSetting({category:ue.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new fe.StringSetting({category:ue.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>pe()?"1":"25"}),imageCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new te.DurationSetting({category:ue.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ne.IntegerSetting({category:ue.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>pe()?32:1024}),quiet:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new fe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:ue.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:ye}),logDir:new fe.StringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:()=>(0,t.isProd)()}),logWebRequests:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new K.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:ue.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,v.noColor)()}),logContextLimit:new ne.IntegerSetting({category:ue.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>64}),logSql:new K.BooleanSetting({category:ue.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new le.OptionalStringSetting({category:ue.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new fe.StringSetting({category:ue.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:ye}),useFsWatch:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:()=>"30s"}),watchDebounceMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (ยฝ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new ce.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:ue.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>U.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new ce.StringArraySetting({aliases:["ignoredMountpoints"],category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:U.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>U.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new K.BooleanSetting({category:ue.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>F.isWin?"15m":"0"}),remoteFilesystemTypes:new ce.StringArraySetting({category:ue.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidFiles:new K.BooleanSetting({category:ue.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new te.DurationSetting({category:ue.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new le.OptionalStringSetting({category:ue.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new fe.StringSetting({category:ue.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ne.IntegerSetting({category:ue.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),trustProxy:new fe.StringSetting({category:ue.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,I.isDocker)()}),cspReportOnly:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new K.BooleanSetting({category:ue.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new le.OptionalStringSetting({category:ue.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new he.StringEnumsSetting({category:ue.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:H.HelmetPlugins}),shortProcessNames:new K.BooleanSetting({category:ue.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!F.isElectron}),commandTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How long should PhotoStructure wait for a command that touches the filesystem (and doesn't do anything computationally expensive)? Note that external hard drives can take 10-15 seconds to spin up, and antivirus apps can hang for tens of seconds on slow machines, so values less than the default may result in undesired timeouts.",defaultValue:()=>"24s"}),minDelayBetweenSpawnMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,P.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),streamFlushMs:new te.DurationSetting({category:ue.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>F.isMac?"100ms":F.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new fe.StringSetting({category:ue.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>y.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new te.DurationSetting({category:ue.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["cpuLoadPercent"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ie.FloatSetting({category:ue.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ne.IntegerSetting({category:ue.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new de.StringEnumSetting({category:ue.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ne.IntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>pe()?50:500,min:1,max:5e3}),enableArchive:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),enableRemove:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ge()}),argon2TimeCost:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ne.IntegerSetting({category:ue.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) ร— argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new K.BooleanSetting({category:ue.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Z.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:ue.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new de.StringEnumSetting({category:ue.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 45 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"45s"}),dbBusyTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.",advanced:()=>!0,defaultValue:()=>"2s"}),dbBackupIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>pe()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:ue.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:pe()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>pe()?.5:30}),dbPageSizeBytes:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ne.IntegerSetting({category:ue.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:256,min:1,max:900}),dbBatchUpsertSize:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:16,min:1,max:500}),dbForceRecover:new K.BooleanSetting({category:ue.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new K.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:ue.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new K.BooleanSetting({category:ue.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!pe()||!(0,I.isDocker)()}),skipHealthCheckIds:new he.StringEnumsSetting({category:ue.SettingCategories.HealthChecks,description:"List of health check IDs to skip. Note that windows skips the 'proc-not-superuser' check by default, as most people on Windows run as an admin user.",defaultValue:F.isWin?["proc-not-superuser"]:[],strEnum:D.HealthCheckIds}),ffmpegHwaccel:new fe.StringSetting({category:ue.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and !0,description:'When transcoding videos, what value should we give to "ffmpeg -threads"?\nNote that there are vanishing returns here: there\'s a substantial benefit to 2 threads versus 1 thread, but 4 vs 8 threads only fractionally improves transcode time while increasing CPU time linearly. The default is clamp(1, 6, ($CPU_COUNT * $cpuBusyPercent) / 4).'}),ffmpegAvcTranscodeArgs:new ce.StringArraySetting({category:ue.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeTimeoutBps:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:'PhotoStructure sets asset file processing timeouts to avoid getting "stuck" when importing problematic files. This setting is the expected worst-case for transcoding, in source video file bytes processed per second. Set this value to 0 to disable video transcode timeouts.',defaultValue:5e4}),transcodeVideos:new K.BooleanSetting({aliases:["transcodeVideo"],category:ue.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320โ€‰ร—โ€‰240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ne.IntegerSetting({category:ue.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840โ€‰ร—โ€‰2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new ce.StringArraySetting({category:ue.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to false on macOS and Raspberry Pis due to instability on those platforms.",defaultValue:()=>!(0,L.isRaspberryPi)()}),enableVipsCache:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new K.BooleanSetting({category:ue.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>F.isLinux}),showFileInFolderCommand:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new fe.StringSetting({category:ue.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new fe.StringSetting({category:ue.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ne.IntegerSetting({category:ue.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new ce.StringArraySetting({category:ue.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new K.BooleanSetting({category:ue.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new K.BooleanSetting({category:ue.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new de.StringEnumSetting({category:ue.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:W.UpdateChannels}),autoUpdateCheck:new K.BooleanSetting({category:ue.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new K.BooleanSetting({category:ue.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new K.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:ue.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new le.OptionalStringSetting({category:ue.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new K.BooleanSetting({category:ue.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ne.IntegerSetting({category:ue.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),minStreamCorrPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new ce.StringArraySetting({category:ue.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ne.IntegerSetting({category:ue.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new K.BooleanSetting({category:ue.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new K.BooleanSetting({category:ue.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new de.StringEnumSetting({category:ue.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncReportsDir:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nOn a reasonable server and disk, these tasks should take a handful of seconds, but the default allows for a (busy!) RPi on a slow, remote disk to not timeout.",defaultValue:()=>"2m"}),scanLibraryFirst:new K.BooleanSetting({aliases:["syncLibraryFirst"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new K.BooleanSetting({aliases:["syncLibraryLast"],category:ue.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new ce.StringArraySetting({category:ue.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),assetSubdirectoryDatestampFormat:new fe.StringSetting({category:ue.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncIntervalHours:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Sync,description:'This setting has been replaced by "syncNewIntervalMs" and "syncChangedIntervalMs".',deprecated:!0}),syncNewIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"1d"}),syncChangedIntervalMs:new te.DurationSetting({category:ue.SettingCategories.Sync,description:"This value controls both how often the sync process discovers new or changed files for any given volume.\nNote that this value is the duration between the last completion time and when the next sync should be scheduled.\nWARNING: Setting this value to a small value will mean PhotoStructure is constantly scanning your disks, which will add wear and tear and possibly reduce the lifespan of your storage media.",defaultValue:"7d"}),retryEnqueued:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'After finishing a directory sync, should PhotoStructure look at recent sync-reports and retry files that are "stuck" in "enqueued" state?\nThis shouldn\'t be necessary, but it\'s a backstop to ensure syncs are comprehensive.',defaultValue:!1}),forceRebuildLibrary:new K.BooleanSetting({category:ue.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),dropWorkQueues:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceSync:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),noModelUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!1}),maxDuplicatePathElements:new ne.IntegerSetting({category:ue.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),noAssetFileUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated AssetFiles be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),noAssetUpdates:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should outdated Assets be ignored on startup? (Only used for tests).",defaultValue:!1,transient:!0}),resyncAssetOnVisit:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!pe()||(0,G.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new K.BooleanSetting({category:ue.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),matchSidecarsCaseInsensitively:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new fe.StringSetting({category:ue.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',defaultValue:"xmp"}),writeMetadataToSidecarsIfImage:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new K.BooleanSetting({category:ue.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new de.StringEnumSetting({category:ue.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:J.AggregateTypes.intersection,strEnum:J.AggregateTypes}),useImageHashes:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new K.BooleanSetting({category:ue.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new fe.StringSetting({category:ue.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ne.IntegerSetting({category:ue.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>u.minuteMs}),fuzzyDatePrecisionCoeff:new ie.FloatSetting({category:ue.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ee.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new de.StringEnumSetting({aliases:["delta_e"],category:ue.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:X.ColorDistanceFunctions.ciede2000,strEnum:X.ColorDistanceFunctions}),dominantColorKmeansRuns:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:Q.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their ฮ”e is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),sharedStateDir:new le.OptionalStringSetting({category:ue.SettingCategories.Events,description:"PhotoStructure uses a set of JSON files to relay messages between processes (rather than an RPC mesh, socket, or named pipe, whose device types isn't supported on some filesystem types). This directory must be readable and writable.",defaultValue:()=>""}),sharedStatePollMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:'The "sharedStateFile" is watched for changes using your OS\'es filesystem watch functionality: for most setups, this will result in almost instantaneous event propagation. Some filesystems don\'t support filesystem watching, or miss file edits, so we _also_ manually check for file changes every "sharedStatePollMs" milliseconds. This defaults to 7 seconds, but know that this will prevent the "PS_CONFIG_DIR" hard drive from spinning down and going to sleep.\nSee the "allowFilesystemSleep" for other related settings.\nSet this setting to 0 to disable state polling.',defaultValue:()=>"7s"}),sharedStateTaskTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Events,description:"How long should PhotoStructure wait for shared-state tasks to be completed before timing out and giving up?",defaultValue:()=>"5m"}),previewQuality:new Z.BoundedIntegerSetting({aliases:["jpegQuality"],category:ue.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new K.BooleanSetting({category:ue.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new K.BooleanSetting({aliases:["jpegMinimized"],category:ue.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!pe()||(0,G.cpuCount)()>=4}),dcrawEmuArgs:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new de.StringEnumSetting({category:ue.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:k.CropStrategies.attention,strEnum:k.CropStrategies}),videoFrameAtSec:new ie.FloatSetting({category:ue.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new K.BooleanSetting({aliases:["sharpen"],category:ue.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(c.FitSizes.values,["uhd8k","uhd5k"]),strEnum:c.FitSizes}),embeddedPreviews:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ne.IntegerSetting({category:ue.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,f.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(F.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new he.StringEnumsSetting({category:ue.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:$.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:ue.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new K.BooleanSetting({category:ue.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new ce.StringArraySetting({category:ue.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>R.DefaultIncludedPreviewTags}),disableAllFilters:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new K.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:ue.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),respectFileExtensions:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ne.IntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new oe.OptionalFloatSetting({category:ue.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ae.OptionalIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ne.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*f.KB}),maxAssetFileSizeBytes:new ne.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:ue.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*f.GB}),validateJpegImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new de.StringEnumSetting({category:ue.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:O.SharpFailOns.truncated,strEnum:O.SharpFailOns}),validateRawImages:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present.\nSee the Enabling this feature slows down imports.",defaultValue:!0}),validateMimetypeSkiplist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new K.BooleanSetting({category:ue.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new ce.StringArraySetting({category:ue.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.DefaultCapturedAtTagsConst}),useMWG:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:N.ProblematicCapturedAtTags}),badDates:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new le.OptionalStringSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new ce.StringArraySetting({category:ue.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>b.DefaultTimezoneSuffixes}),fuzzyDateParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ne.IntegerSetting({category:ue.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:re.MinValidYear}),useStatToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new de.StringEnumSetting({category:ue.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:me.TagInferenceSettingValues,defaultValue:me.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ie.FloatSetting({category:ue.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Z.BoundedIntegerSetting({category:ue.SettingCategories.Filters,description:"What's the minimum case-insensitive Sรธrensenโ€“Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),writeInferredTagsToLibraryCopies:new K.BooleanSetting({category:ue.SettingCategories.Parsing,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),recountAllTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:A.DateTagFormats.ym,strEnum:A.DateTagFormats}),tagDateFromStat:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!pe()}),tagKeywordsFromPath:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:B.KeywordReparentingStrategies.move,strEnum:B.KeywordReparentingStrategies}),rootTagAlbumsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhoAliases:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new le.OptionalStringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "ObjectsโŠƒToolsโŠƒHammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>โŠƒ"}),tagFileType:new K.BooleanSetting({category:ue.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagJsonFaces:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:V.NameTagFormats["as-is"],strEnum:V.NameTagFormats}),tagNamesDefaultFamily:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new de.StringEnumSetting({category:ue.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:z.NameTagOrders}),tagNamesSurnamePrefixes:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","Dโ€™","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","ten","ter","Van โ€˜t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new fe.StringSetting({category:ue.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!pe()||!(0,I.isDocker)()}),tagDisplayNameFSLabels:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new ce.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:ue.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new ce.StringArraySetting({category:ue.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new K.BooleanSetting({category:ue.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new te.DurationSetting({category:ue.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new K.BooleanSetting({category:ue.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new le.OptionalStringSetting({category:ue.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,d.entries)(t.Settings))i._setName(e);function ve(e){const i=((0,l.blank)(e)?"":e).split(r.delimiter);return(0,I.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(l.notBlank).join(r.delimiter)}function we(e){return["system"===e.categoryType?0:1,ue.SettingCategories.indexOf(e.category)??ue.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=ve,t.pathWithDefaults=(0,s.lazy)((()=>ve((0,C.getEnv)("PATH")))),t.allSettings=(0,s.lazy)((()=>(0,a.sortBy)((0,d.values)(t.Settings),we))),t.persistedSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,s.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,s.lazy)((()=>(0,t.persistedSettings)().filter((e=>ue.LibraryCategories.includes(e.category)))));const Se=(0,s.lazy)((()=>{const e=new p.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Se().get((0,m.toS)(e).toLowerCase())},t.ciSettings=(0,s.lazy)((()=>new g.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},95699:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(4866),r=i(19658),s=i(1629),o=i(4586),a=i(58676),l=i(5739),u=i(35796),c=i(18226),d=i(20902),h=i(82166),f=i(98462),m=i(88462),p=i(15203),g=i(38846),y=i(59387),v=i(43414);t.setSettingsDefaults=(0,n.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=u.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=s.defaultCacheDir,v.Settings.sharedStateDir.opts.defaultValue=()=>(0,h.DefaultSharedStateDir)()?.nativePath,v.Settings.toolPaths.opts.defaultValue=()=>(0,d.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>r.isProd&&(0,p.isDocker)()?a.DefaultDockerLibraryDir:r.isTest?"/home/test/Pictures":(0,c.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=l.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=l.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,c.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,y.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel}))},85560:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},70338:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(49411),r=i(11944),s=i(39938),o=i(87748),a=i(66776),l=i(39784),u=i(84161);function c(e){return null==e?void 0:(0,o.stringify)(e)}t._join=c;function d(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["ยฆ",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=d;class h extends u.Setting{constructor(e){super({defaultValue:[],fromEnv:d,toEnv:c,...e})}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return this.value??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}}t.StringArraySetting=h},35195:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(84161);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},39165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(11944),r=i(87748),s=i(66776),o=i(70338);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,o.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},24354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(39938),r=i(91464),s=i(84161);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=o},98024:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(49411),r=i(66776),s=i(4586),o=i(85560);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,o.SettingsToml)))}},96879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(84253);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},13060:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(81627),r=i(44470),s=i(39938),o=i(83486),a=i(7162),l=i(91464),u=i(51081),c=i(95725),d=i(63410),h=i(38049);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},38049:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(39938),r=i(1429),s=i(87748),o=i(61570),a=i(44726);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,a.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},16704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},69301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(81666),r=i(91464);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},11579:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(84253);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},82590:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},55267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},98788:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtlรคnder","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},17310:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(84253);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},63526:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(4866),r=i(11944),s=i(1429),o=i(89253),a=i(61570),l=i(44726),u=i(82798),c=i(25015),d=i(703),h=i(17310);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,a.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},61659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(84253);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},40185:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(84253);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},32994:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(84253);t.NameTagOrders=(0,n.strEnum)("western","eastern")},78362:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(11944),r=i(39938),s=i(66776),o=i(91464),a=i(46852),l=i(85943),u=i(25015),c=i(81666),d=i(43414),h=i(63526);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isExt)(i.ext,"json"),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;let m=e.base,p=i.name;if(f(m,p,{ignoreCase:l}))return!0;if(f(e.name,p,{ignoreCase:l}))return!0;const g=(0,s.map)((0,u.normalizeExt)(e.ext),(e=>(0,u.extAliases)().get(e)));if(null!=g){const e=(0,u.mkExtsRegExp)(g);if(m=m.replace(e,""),p=p.replace(e,""),f(m,p,{ignoreCase:l}))return!0}const y=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(y)for(const t of(0,n.uniq)([m,e.name,(0,h.stripExt)(m),(0,h.stripExt)(e.name)]))for(const e of(0,n.uniq)([p,i.name,(0,h.stripExt)(p),(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:y}))return!0;return a&&function(e,i){const n=(0,o.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function s(e){return(0,r.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(n.length)),l=s(i.slice(n.length));return a&&l}(m,p)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},3874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(1429),a=i(49049),l=i(39784),u=i(7162),c=i(46852),d=i(76531),h=i(46573),f=i(19209),m=i(25116),p=i(26682),g=i(55713),y=i(30848),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},19209:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(49411),r=i(47261),s=i(46850),o=i(39938),a=i(66776),l=i(44726),u=i(82669),c=i(82798),d=i(13779),h=i(51053),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=(0,a.orElse)(t,g),this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,(0,a.orElse)(i,g)),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=(0,a.orElse)(r,g),function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===n&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(n,r,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?M:_;let n="";const{scheme:r,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>n+="?"+e)),a&&(n+="#",n+=t?a:_(a,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=E;const C=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(C)?e.replace(C,(e=>T(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},25116:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(4866),r=i(11944),s=i(24603),o=i(49049),a=i(82798),l=i(7162),u=i(3874),c=i(19209),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},26682:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(49411),r=i(39938),s=i(44726),o=i(49049),a=i(3955),l=i(1391),u=i(51053),c=i(46573),d=i(19209),h=i(47044);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},55713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(11944),r=i(39938),s=i(44726),o=i(49049),a=i(82341),l=i(3955),u=i(98250),c=i(43414),d=i(19209);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},30848:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(49411)),a=i(39938),l=i(49049),u=i(39784),c=i(91464),d=i(1391),h=i(76531),f=i(58659),m=i(51053),p=i(46573),g=i(19209);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,a.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?o.join(t,...r):void 0}},47044:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(39938),r=i(88491),s=i(81765),o=i(29731);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},38846:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(42041),r=i(39036);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},39036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(84253);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},39206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(11944),r=i(14195),s=i(3955),o=i(51053),a=i(43414);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},86115:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(15203);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},36738:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69329:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(4866),r=i(39938),s=i(39784),o=i(7162),a=i(2023),l=i(63410),u=i(15203),c=i(43414),d=i(39206),h=i(7903),f=i(36736),m=i(55412),p=i(32421),g=i(10609),y=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},7903:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(17078),l=i(82128),u=i(7162),c=i(69317),d=i(51053),h=i(53719),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},69551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(39938),a=i(1429),l=i(66776),u=i(75556),c=i(61570),d=i(44726),h=i(39784),f=i(82798),m=i(7162),p=i(91464),g=i(46852),y=i(17875),v=i(71663),w=i(43414),S=i(49829),b=i(76019),P=i(53719),_=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(M)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function C(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function F(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,a.flatten)(t).map(C)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,r.compact)((0,a.flatten)(n).map(I)),l=(0,r.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},36736:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(88491),a=i(43947),l=i(66776),u=i(98510),c=i(7162),d=i(55568),h=i(14889),f=i(91464),m=i(97503),p=i(46852),g=i(37121),y=i(69317),v=i(98462),w=i(9288),S=i(76531),b=i(15203),P=i(51053),_=i(7903),M=i(55412),E=i(62255),x=i(53719);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeout)((async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await C(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))}),(0,x.mountpointsTtlMs)(),(()=>T().warn("gioVolumes(): timed out after "+x.mountpointsTtlMs+"ms")),(e=>T().log((0,r.isEmpty)(e)?"debug":"info","gioVolumes()",{result:e}))))),(0,a.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const C=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},55412:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(4866),r=i(92585),s=i(43947),o=i(7383),a=i(49379),l=i(79015),u=i(43414),c=i(32421),d=i(53719);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},11142:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(4866),r=i(11944),s=i(39938),o=i(75556),a=i(7162),l=i(2023),u=i(14889),c=i(91464),d=i(69317),h=i(28649),f=i(51081),m=i(63410),p=i(9483),g=i(15203),y=i(7903),v=i(55412),w=i(53719),S=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...r,...s},u=n?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),n=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},71820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(55543),r=i(4866),s=i(11944),o=i(39938),a=i(38625),l=i(66776),u=i(26588),c=i(39784),d=i(7162),h=i(46852),f=i(37121),m=i(69317),p=i(7903),g=i(55412),y=i(53719),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeout)((0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),i,(()=>v().warn("Timeout: failed to get disk metadata for "+e)))}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},32421:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(4866),r=i(11944),s=i(59694),o=i(88491),a=i(43947),l=i(20636),u=i(7162),c=i(19658),d=i(99869),h=i(55568),f=i(14889),m=i(91464),p=i(36079),g=i(46852),y=i(7383),v=i(69317),w=i(95298),S=i(17875),b=i(56958),P=i(79015),_=i(95725),M=i(76531),E=i(51053),x=i(43414),T=i(39206),C=i(36736),D=i(62255),k=i(49829),O=i(10609),I=i(53719),F=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function L(){t.mountpoints.unset(),t.mountpoints_.unset()}function A(e=(0,I.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function N(){L(),(0,h.isSyncService)()&&await(0,b.broadcastEvent_)("mountpointsChanged")}t.localMountpointSetup=(0,n.lazy)((async()=>{x.Settings.libraryDir.watchLater(L),x.Settings.scanPaths.watchLater(L),(0,h.isSyncService)()?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),A((0,I.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux&&(await(0,D.maybeWatchProcMounts)(),await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),await j()&&(e.info("Setting up Linux findmnt mount monitor"),A((0,I.volumeMetadataTtlMs)()),(0,t.findmntPoll)()))}),30*o.secondMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=x.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,I.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,O.isExcludedMountpoint)(e)||x.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,_.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,a.later)((()=>{(0,P.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),L()})),x.Settings.mountpointsTtlMs.watch(A)}),c.isTest?1:o.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>N(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),N()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const j=(0,n.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,I.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>N(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},62255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(4866),r=i(11944),s=i(88491),o=i(13779),a=i(7162),l=i(55568),u=i(14889),c=i(91464),d=i(46852),h=i(86472),f=i(13348),m=i(76531),p=i(9483),g=i(51053),y=i(43414),v=i(7903),w=i(36736),S=i(32421),b=i(10609),P=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,d.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,w.isGioSupported)())try{await(0,d.thenMap)((0,w.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){P().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!y.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,b.isExcludedMountpoint)(e)&&(!y.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=M,i=E){if(g.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,c.unoctal)(i)]:void 0}))),a=await(0,d.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return P().tap({level:p.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return P().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void P().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=x,t.maybeWatchProcMounts=(0,n.lazy)((async()=>g.isLinux&&(0,l.isSyncService)()&&!await(0,m.isEmptyFile)(_)?new h.FsWatcher({target:_,maxPollIntervalMs:s.minuteMs,onChange:()=>{P().info("detected change in "+_),S.mountpoints.unset()},initialDelayMs:u.ShortCommandTimeoutMs,sha:!0}):void 0))},49829:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(4866),r=i(88491),s=i(20636),o=i(7162),a=i(14889),l=i(91464),u=i(69317),c=i(9288),d=i(71663),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},10609:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(4866),r=i(39938),s=i(7162),o=i(81765),a=i(19658),l=i(3955),u=i(51053),c=i(43414),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||a.isTest?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||a.isTest?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||a.isTest?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||a.isTest?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},92002:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(39938),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},76019:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(11944),r=i(39938),s=i(88491),o=i(66776),a=i(98510),l=i(82798),u=i(46852),c=i(69317),d=i(82128),h=i(9288),f=i(48783),m=i(2023),p=i(51053),g=i(71663),y=i(91464),v=i(55412);t.addRemoteVolumeInfoWin=async function(e,t){if(!p.isWin)throw new Error("wtf");return await(0,u.thenMap)((0,o.orElse)(t,(()=>E())),(t=>{const i=(0,f.toMap)(t,(e=>[e.mountpoint,e]));e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,r.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,m.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,h.wmic)(),t=await(0,c.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,d.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,y.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await g.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,y.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},53719:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(88491),r=i(17078),s=i(43414);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.commandTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},27127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(38625),a=i(43947),l=i(20636),u=i(31737),c=i(7162),d=i(19658),h=i(91464),f=i(70259),m=i(79015),p=i(51081),g=i(98250),y=i(15203),v=i(43414),w=i(32421),S=i(53719),b=i(21954),P=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),_=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,S.commandTimeoutMs)()})));function M(e){return(0,o.isTrue)(e.ignorable)||(0,y.isDocker)()&&"/"===e.mountpoint||d.isTest&&"node_modules"===(0,n.basename)(e.mountpoint)}function E(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,S.commandTimeoutMs)());for(const e of(0,p.splitLines)(t)){const t=E(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function T(e){if(v.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of v.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountpoint).join(t),n=await x(i).catch((e=>P().info("Failed to read "+i,{error:e})));if(null!=n)return P().tap({msg:"Serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}if("/"===e.mountpoint)return e.uuid;if(v.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,b.writeVolumeUuid)(e);if(null!=t)return t}return e.uuid}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>_.clear())),w.mountpoints.watchLater((()=>_.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(M(e))return;if((0,o.isFalse)(e.ok))return;const t=await _().getOrSetAsync(e.mountpoint,(async()=>T(e)));null!=t&&(e.uuid=t)}(e),(0,S.commandTimeoutMs)(),(()=>P().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,S.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=M,t.toVolumeUUID=E,t.readUuidFile_=x,t.readVolumeUUID=T},46573:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(70612)),s=n(i(49411)),o=i(4866),a=i(11944),l=i(59694),u=i(39938),c=i(38625),d=i(88491),h=i(43947),f=(i(24603),i(6314)),m=i(66776),p=i(75556),g=i(98510),y=i(20636),v=i(90957),w=i(39784),S=i(13779),b=i(7162),P=i(19658),_=i(55568),M=i(91710),E=i(14889),x=i(91464),T=i(46852),C=i(37121),D=i(1629),k=i(14195),O=i(42648),I=i(29405),F=i(20902),L=i(17875),A=i(79141),N=(i(79015),i(77390)),R=i(19653),j=i(3955),B=i(98250),V=i(95725),z=i(76531),W=i(18501),U=i(58659),q=i(15203),H=i(51053),G=i(43414),J=i(47044),$=i(69329),K=i(69551),Y=i(55412),Z=i(11142),X=i(71820),Q=i(32421),ee=i(92002),te=i(76019),ie=i(53719),ne=i(27127),re=(0,o.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=r.default.platform(),oe=new Map,ae=new Map,le=new Map;function ue(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,J.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ce(e){if(null!=e)return ue(e.mountpoint,e,oe),ue((0,J.volsha)(e.uuid),e,le),e}function de(){return(0,a.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,Y.lazyFsAsync)("mountpointToVolsha",(async()=>(await he(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),oe.clear(),le.clear(),he.unset(),t.cachedVolumes.unset(),e&&await Promise.all(de().map((e=>e.rmrf())))};const he=(0,Y.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(de().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ce);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,x.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ce),e}));async function fe(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,q.isDocker)()?{}:{fromHost:(0,W.cleanHostname)()},updatedAt:n,os:se}))),s=new Map;for(const e of r)for(const t of(0,a.compactBlanks)([(0,J.volsha)(e.uuid),(0,J.volsha)(e.mountpoint)]))s.set(t,e);const o=de();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function me(){const e=await(0,t.cachedVolumes)();if((0,_.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,Q.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function pe(e,i){const n=(0,m.map)(e,V.toNativePath_);if((0,u.blank)(n))return;const r=await(0,N.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:he}]){const t=await(0,v.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,j.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return re().debug("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function ge(e,t,i){const n=i.filter((e=>(0,x.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,x.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,U.friendlyname)(e);return(0,T.asyncFind)(n,(async e=>(0,x.equalsIgnoreCase)(s,await(0,U.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,_.isSyncService)()||P.isTest)),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await he()),t=(0,w.toA)(await(0,Q.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,a.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=me,t.volumes=(0,Y.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeout)(me(),(0,ie.commandTimeoutMs)());if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,y.thenOrTimeoutError)((0,t.volumesImpl)(),(0,ie.commandTimeoutMs)());if((0,a.isNotEmpty)(i))return i}catch(e){(0,L.onError)((0,A.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if(P.isTest){const e=(0,p.toInt)((0,I.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,O.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeout)(H.isWin?(0,K.dfWin)():(0,$.dfPosix)(),(0,ie.mountpointsTtlMs)(),(()=>(0,L.onError)("Timed out getting local volume metadata")));if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,ie.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeout)(H.isWin?(0,te.addRemoteVolumeInfoWin)(t):(0,ee.addRemoteVolumeInfoPosix)(t),10*d.secondMs).catch((e=>{(0,L.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ne.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:n}),n.forEach(ce),await fe(n),Object.freeze(n)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,x.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return pe((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,S.greatestBy)(t.filter((t=>(0,j.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=pe,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:he},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,J.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>ge(e,i,t)))},t.bestRemoteVolume=ge,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return le.get(e)??(await he())?.find((t=>(0,J.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,J.volsha)(t.uuid)===e))}},21954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(49411),r=i(4866),s=i(39938),o=i(7162),a=i(42041),l=i(76531),u=i(47987),c=i(76474),d=i(43414),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},17679:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(84253);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},3331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(49411),r=i(4866),s=i(89253),o=i(91464),a=i(51081),l=i(27175),u=i(95998),c=i(19702);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},19702:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(39938),r=i(1429),s=i(89253),o=i(39784),a=i(91464),l={a:["4","@","ะ”"],b:["8","6","ะช"],c:["[","(","ยฉ"],e:["3","โ‚ฌ"],f:["ฦ’"],g:["9"],i:["1","!","|"],l:["1","ยฃ"],o:["0"],s:["5","$"],t:["7","+","โ€ "],x:["ร—"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},75153:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(70612)),s=i(4866),o=i(88491),a=i(75556),l=i(7162),u=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},21003:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(70612)),s=i(4866),o=i(75556),a=i(17078),l=i(7162),u=i(4931),c=i(6667),d=i(15203),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},67220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resume=t.pause=t.isPaused=void 0;const n=i(79015);let r=!1;function s(){r&&(r=!1,(0,n.ee)().emit("clearCache"),(0,n.ee)().emit("resume"))}t.isPaused=function(){return r},t.pause=function(e=!0){!1===e?s():r||(r=!0,(0,n.ee)().emit("pause"))},t.resume=s},59387:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(4866),r=i(88491),s=i(43947),o=i(75556),a=i(17078),l=i(7162),u=i(19658),c=i(79015),d=i(9483),h=i(43649),f=i(43414),m=i(75153),p=i(21003),g=i(98023),y=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function v(){p.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),t.sharpThreadsPerProcess.unset(),m.cpuCount.unset()}(0,s.later)((()=>{u.isTest&&(0,c.ee)().on("clearCache",(()=>v())),(0,c.ee)().on("settingsChanged",v),f.Settings.cpuBusyPercent.watchLater(v),f.Settings.maxConcurrentImports.watchLater(v)})),t.clearMaxWorkCaches=v;const w=(0,n.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return y().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,p.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.round((0,p.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.round(e/a.MB)}})}),r.minuteMs);function S(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return y().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=S,t.targetCpuLoadPct=b,t.singleThreadMode=function(){return Math.round(b()*(0,m.cpuCount)())<=1||f.Settings.cpuBusyPercent.valueOrDefault<=1||1===(0,t.maxCpus)()},t.maxCpus=(0,n.lazy)((function(){const e=Math.max(1,Math.floor(b()*(0,m.cpuCount)())-1);let t=e;const i=g.timeoutRate.prior()?.eventsPerMinute??0,n=S();if(1!==n){const e=t;t*=n,y().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,w());return t=(0,o.clamp)(1,r,Math.ceil(t)),y().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,m.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):(0,t.maxCpus)()})),t.sharpThreadsPerProcess=(0,n.lazy)((()=>{const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.floor((0,h.lerp2d)((0,t.maxCpus)(),{x:1,y:1},{x:6,y:2})))}))},98023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(5712),r=i(92332),s=i(4866),o=i(88491),a=i(43947),l=i(7162),u=i(19658),c=i(14889),d=i(79015),h=i(69547),f=i(59387),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*o.minuteMs,u.isTest?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},11944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(59694),r=i(39938),s=i(24603),o=i(87748),a=i(21040),l=i(8199),u=i(23175),c=i(90957),d=i(47025),h=i(39784),f=i(82798);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,a.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(11944),r=i(14439),s=i(20810),o=i(87748),a=i(21040),l=i(66776),u=i(8199),c=i(39784);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,a.getOrSet)(i,(0,o.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(47025);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},92585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(43947),r=i(75556),s=i(20636),o=i(50530);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},37609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},39938:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(66776),r=i(90957),s=i(82798);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38625:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},37589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(87748);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},88491:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(11944),r=i(39938),s=i(11448),o=i(66776),a=i(75556),l=i(65113),u=i(44726),c=i(17078);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},81003:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},85120:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38625),r=i(83965);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function o(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function a(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return o(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r}},43947:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(88491),r=i(1894),s=i(75556),o=i(61570);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},24603:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eql=void 0;const n=i(85120),r=i(47025);function s(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function o(e,t){return(0,r.isFunction)(e)&&(0,r.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=function(e,t){return(0,n.deepEql)(e,t,{comparator:u})},t.dateComparator=s,t.functionComparator=o;const a=[s,o],l=new Map;function u(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=l.get(i);if(null!=n)return n(e,t)??null}for(const i of a){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){a.push(e)},t.unshiftObjComparator=function(e){a.unshift(e)},t.setFieldComparator=function(e,t){l.set(e,t)}},16475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(11944),r=i(39938),s=i(1429),o=i(75556),a=i(61570),l=i(82798);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},1429:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(39784);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},19067:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(11944),r=i(88491),s=i(66776),o=i(75556),a=i(17078),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},51367:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(11944);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},97042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(84253);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},20810:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(75556);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(81003),Error_1=__webpack_require__(16475),Maybe_1=__webpack_require__(66776),isFunction_1=__webpack_require__(47025);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,o,a,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.revive=revive},6314:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0,t.Latch=class{constructor(e){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},11448:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(11944),r=i(24603),s=i(75556),o=i(11353);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,a=await i;if(!(0,r.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},66776:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(90957),r=i(82798);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return a(o(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},89253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(11944),r=i(59694),s=i(24603),o=i(87748),a=i(21040),l=i(66776),u=i(44726),c=i(39784);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}flatValues(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=r.length;(0,n.filterInPlace)(r,(t=>e(i,t))),t=t||s!==r.length,0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},1894:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},75556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.mapIntOr=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=t.fmtPct=void 0;const n=i(59694),r=i(39938),s=i(66776),o=i(90957),a=i(82798);function l(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}t.isNumber=l,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const u=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(u)};const c=/[^-.\d\s]/;function d(e){return"bigint"==typeof e}function h(e,t){return l(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(c)&&null!=w(e)},t.isBigInt=d,t.mapFinite=h;const f=e=>(t,i)=>l(t)&&l(i)&&e(t,i);function m(e,i,r){return!(null==r||!l(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function p(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function y(e,t){if((0,r.blank)(e))return t.defaultValue;if(l(e))return t.nton(e);if(d(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||ep(e),ston:parseInt,...t})}function w(e,t){return y(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function S(e){return l(e)&&e>0}function b(e){return l(e)&&e>=0}function P(e,t){const i=v(e);return null==i?void 0:t(i)}function _(e,t){return l(e)?t(e):void 0}function M(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function E(e,t){if(null==e)return 0;const i=Math.pow(10,t);return M(e*i)/i}function x(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return m(t-n,t+n,e)},t.within=m,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return l(e)&&e<0},t.gt0=S,t.firstGt0=function(...e){for(const t of e){if(S(t))return t;const e=v(t);if(S(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=P,t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=v(e);return S(t)?String(t):void 0},t.mapIntOr=function(e,t,i){return(0,s.orElse)(P(e,t),i)},t.mapNumeric=_,t.map2Numeric=function(e,t,i){return _(e,(e=>_(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,o.tot)(t)},t.round=M,t.toFixed=function(e,t){try{return _(e,(e=>M(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d+\.\d+)0+$/,"")},t.toPrecision=E,t.toPrecisionMaybe=function(e,t){return h(e,(e=>E(e,t)))},t.sigFigs=function(e,t){if(0===e||0===t)return 0;const i=t-M(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?M(e/n)*n:M(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=x,t.times=function(e,t){if(!S(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return x(0,100,S(t)?M(100*(S(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||m(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t}},61570:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(11944),r=i(59694),s=i(39938),o=i(47025),a=i(66776),l=i(75556),u=i(8199),c=i(83511);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,o]=(0,c.splitFirst)(n,"."),a=b(t,i);null!=a?.value&&r(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,o.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},98510:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},65113:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(75556),r=i(82798),s={};function o(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(39938),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},8199:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(11944),r=i(82798),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),o=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?a.indexOf(n)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},26588:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(39784);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},46234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(84253);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},23175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChar=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(11944),r=i(75556);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return a(e,t,1,i)[0]}function a(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,o=new Set(n??[]);if(t===e&&0===r&&0===o.size&&1===i)return[e];const a=r-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of a(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},7127:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(84253);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},83511:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},84253:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(61570),r=i(90957);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,r.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),n=o(t);return null==i||null==n?void 0:i>n?1:i{const i=o(e);return null==i?void 0:t[i]}}}},44726:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(11944),r=i(37609),s=i(39938),o=i(1429),a=i(20810),l=i(75556),u=i(39784),c=i(82798);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,a.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"โ€ฆ"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.toNotTimeout=t.Timeout=void 0;const n=i(88491),r=i(61570),s=i(90957),o=i(21669);async function a(e,i,n=!0){return(i=Math.round(i??0))<=0?e:new Promise((async(s,o)=>{let a=!0;const l=setTimeout((()=>{a&&(a=!1,s(t.Timeout))}),i);try{n&&(0,r.maybeCall)(l,"unref");const t=await e;a&&(a=!1,s(t))}catch(e){a&&(a=!1,o(e))}finally{clearTimeout(l)}}))}async function l(e,i,r=!0){const s=await a(e,i,r);if(s===t.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(i)+")");return s}t.Timeout=Symbol("timeout"),t.toNotTimeout=function(e){return e===t.Timeout?void 0:e},t.thenOrTimeout=a,t.thenOrTimeoutAt=async function(e,i,n=!0){const r=i-Date.now();return r<=0?t.Timeout:a(e,r,n)},t.thenOrOnTimeout=async function(e,t,i){return new Promise((async(n,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),n(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=l,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return l(e,r,i)},t.thenOrTimeoutAs=async function({f:e,timeoutMs:i,as:n,unref:r=!0}){const o=await a(e,i,r);return o===t.Timeout?(0,s.tot)(n):o}},90957:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(47025);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},21669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},49049:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},82669:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(11944),r=i(39938),s=i(82798);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},17078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(39938),r=i(11448),s=i(75556),o=i(71756),a=i(84253),l=i(44726),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),o=d[n];return(0,s.sigFigs)(e/r,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),o=h[n];return(0,s.sigFigs)(e/r,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):c(e)+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},11353:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(61570);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},47025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},39784:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toA=void 0;const n=i(20810),r=i(44726);t.toA=function(e){return Array.isArray(e)?e:null==e?[]:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}},50530:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(11944),r=i(22840),s=i(39784),o=i(82798);function a(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(a))}},82798:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(87748);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},87978:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(7304),s=n(i(87561)),o=n(i(49411)),a=i(97742),l=i(42041),u=i(79682),c=i(38507);function d(e){for(const t of["bin",__dirname]){const i=o.default.join(t,e);if(s.default.existsSync(i))return i}return console.error("failed to find command "+e),e}r.program.version(l.version),r.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,c.verifyUidGid)(),(0,u.addFooter)(r.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:d("main.js")}).command("info",u.CliDesc.info,{executableFile:d("info.js")}).command("list",u.CliDesc.list,{executableFile:d("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:d("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:d("logtail.js")}).command("web",u.CliDesc.web,{executableFile:d("web.js")}).command("sync",u.CliDesc.sync,{executableFile:d("sync.js")}).parse(a.argv)},81627:e=>{e.exports=require("@iarna/toml")},1487:e=>{e.exports=require("@parcel/watcher")},5712:e=>{e.exports=require("batch-cluster")},7304:e=>{e.exports=require("commander")},71239:e=>{e.exports=require("events")},44470:e=>{e.exports=require("fs-extra")},1604:e=>{e.exports=require("he")},42748:e=>{e.exports=require("luxon")},55543:e=>{e.exports=require("plist")},46850:e=>{e.exports=require("punycode")},83965:e=>{e.exports=require("type-detect")},17718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},30604:e=>{e.exports=require("node:dns")},87561:e=>{e.exports=require("node:fs")},93977:e=>{e.exports=require("node:fs/promises")},70612:e=>{e.exports=require("node:os")},49411:e=>{e.exports=require("node:path")},90410:e=>{e.exports=require("node:path/posix")},97742:e=>{e.exports=require("node:process")},84492:e=>{e.exports=require("node:stream")},76402:e=>{e.exports=require("node:stream/promises")},92332:e=>{e.exports=require("node:timers")},47261:e=>{e.exports=require("node:util")},65628:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(87978);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/public/3rd-party-licenses.txt.gz b/public/3rd-party-licenses.txt.gz index 4d04053ac0fed38839e55124e1311b94a8a26450..ef56fe912b7fcdcab2b26fdd187b6e87f6d605b4 100644 GIT binary patch delta 17 ZcmX^1f$7)>CN}wQ4i2?98`&Io002YM2J!#^ delta 17 ZcmX^1f$7)>CN}wQ4i3Y+8`&Io002YD2JQd= diff --git a/public/app/about.css.gz b/public/app/about.css.gz index 51dbdfc09f40155df3182116f3a8f65f7900528f..8237d99e2b4d35e4f0272e69601629ee38698755 100644 GIT binary patch delta 15 Wcmew;`%#unzMF$X;}y21_mFC2naFkfd;h(0n%&`ts@+O2x2Zbdi7?%-)uDox9DsETuBK0 Kf`ptYvjqSm1{8Pz delta 52 zcmV-40L%Z(>;}y21_mFC2namgfd;h(0n%&`tRozN2x2Zbdi7?%*KZHnx9DsETuBHj Ka+2C9vjqSqG!%va diff --git a/public/app/health.css.gz b/public/app/health.css.gz index 845fda0b3c998f2c002fe34fdaaf895b94f2f5b3..a921b4ff41ab94776d60e7a341392971bad2eda3 100644 GIT binary patch delta 15 WcmX@6bxey*zMF$XjkO+ delta 15 WcmaE=|5Tq%zMF%?=ia72JjzMF$Xia72JjzMF%?=Wek`0#zMF%?@XbcH1KI#DqXoJE delta 15 WcmX>Wek`0#zMF%?=I%ze1KI#DngzB1 diff --git a/public/app/splash.css.gz b/public/app/splash.css.gz index 1683847aabd4f19ff44f97eb80a54bce516327e5..68800f169de66e18850391b4d1d90e79eb3e1403 100644 GIT binary patch delta 15 WcmZqRZs2B<@8;mpc(akMiWLAKTLd8h delta 15 WcmZqRZs2B<@8;kzy1S9BiWLAKOavSN diff --git a/public/app/splash.css.map.gz b/public/app/splash.css.map.gz index 3eed84e52d860d5ab87c310e54f9ae851d058ac4..0dd16a2be4ecef34a3290bd001d00c45bcc929b3 100644 GIT binary patch delta 15 WcmZ3-vW|sKzMF$X